Java Code Examples for org.fisco.bcos.web3j.abi.FunctionEncoder#encode()

The following examples show how to use org.fisco.bcos.web3j.abi.FunctionEncoder#encode() . 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: RevertResolverTest.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void hasRevertMessageTest() throws IOException {
    String revertMessage = "RevertMessage";
    Function revertFunction = newFunction("Error", revertMessage);
    String revertABI = FunctionEncoder.encode(revertFunction);

    Function testFunction = newFunction("testFunc", revertMessage);
    String testABI = FunctionEncoder.encode(testFunction);

    assertFalse(RevertResolver.hasRevertMessage(null, null));
    assertFalse(RevertResolver.hasRevertMessage("", null));
    assertFalse(RevertResolver.hasRevertMessage(null, ""));
    assertFalse(RevertResolver.hasRevertMessage("", ""));
    assertFalse(RevertResolver.hasRevertMessage("0x0", ""));
    assertFalse(RevertResolver.hasRevertMessage("0x0", ""));
    assertFalse(RevertResolver.hasRevertMessage("0x0", revertABI));
    assertTrue(RevertResolver.hasRevertMessage("0x1", revertABI));
    assertFalse(RevertResolver.hasRevertMessage(null, revertABI));

    assertFalse(RevertResolver.hasRevertMessage("0x0", testABI));
    assertFalse(RevertResolver.hasRevertMessage("0x1", testABI));
    assertFalse(RevertResolver.hasRevertMessage(null, testABI));
}
 
Example 2
Source File: RevertResolverTest.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void hasRevertMessageSMTest() throws IOException {
    EncryptType.setEncryptType(EncryptType.SM2_TYPE);
    String revertMessage = "RevertMessage";
    Function revertFunction = newFunction("Error", revertMessage);
    String revertABI = FunctionEncoder.encode(revertFunction);

    Function testFunction = newFunction("testFunc", revertMessage);
    String testABI = FunctionEncoder.encode(testFunction);

    assertFalse(RevertResolver.hasRevertMessage(null, null));
    assertFalse(RevertResolver.hasRevertMessage("", null));
    assertFalse(RevertResolver.hasRevertMessage(null, ""));
    assertFalse(RevertResolver.hasRevertMessage("", ""));
    assertFalse(RevertResolver.hasRevertMessage("0x0", ""));
    assertFalse(RevertResolver.hasRevertMessage("0x0", ""));
    assertFalse(RevertResolver.hasRevertMessage("0x0", revertABI));
    assertTrue(RevertResolver.hasRevertMessage("0x1", revertABI));
    assertFalse(RevertResolver.hasRevertMessage(null, revertABI));

    assertFalse(RevertResolver.hasRevertMessage("0x0", testABI));
    assertFalse(RevertResolver.hasRevertMessage("0x1", testABI));
    assertFalse(RevertResolver.hasRevertMessage(null, testABI));
    EncryptType.setEncryptType(EncryptType.ECDSA_TYPE);
}
 
Example 3
Source File: RevertResolverTest.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void isOutputStartWithRevertMethodSMTest() {
    EncryptType.setEncryptType(EncryptType.SM2_TYPE);
    String revertMessage = "isOutputStartWithRevertMethodTest";
    Function revertFunction = newFunction("Error", revertMessage);
    String revertABI = FunctionEncoder.encode(revertFunction);

    Function testFunction = newFunction("testFunc", revertMessage);
    String testABI = FunctionEncoder.encode(testFunction);

    assertTrue(RevertResolver.isOutputStartWithRevertMethod(revertABI));
    assertFalse(RevertResolver.isOutputStartWithRevertMethod(testABI));
    assertTrue(RevertResolver.isOutputStartWithRevertMethod(revertABI));
    assertFalse(RevertResolver.isOutputStartWithRevertMethod(testABI));
    EncryptType.setEncryptType(EncryptType.ECDSA_TYPE);
}
 
Example 4
Source File: FiscoBcosBroker4ProducerTest.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
private String buildWeEvent(WeEvent event) throws BrokerException {
    final Function function = new Function(
            Topic.FUNC_PUBLISHWEEVENT,
            Arrays.<Type>asList(new org.fisco.bcos.web3j.abi.datatypes.Utf8String(event.getTopic()),
                    new org.fisco.bcos.web3j.abi.datatypes.Utf8String(new String(event.getContent(), StandardCharsets.UTF_8)),
                    new org.fisco.bcos.web3j.abi.datatypes.Utf8String(JsonHelper.object2Json(event.getExtensions()))),
            Collections.<TypeReference<?>>emptyList());
    return FunctionEncoder.encode(function);
}
 
Example 5
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 6
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 7
Source File: RevertResolverTest.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void isOutputStartWithRevertMethodTest() {
    String revertMessage = "isOutputStartWithRevertMethodTest";
    Function revertFunction = newFunction("Error", revertMessage);
    String revertABI = FunctionEncoder.encode(revertFunction);

    Function testFunction = newFunction("testFunc", revertMessage);
    String testABI = FunctionEncoder.encode(testFunction);

    assertTrue(RevertResolver.isOutputStartWithRevertMethod(revertABI));
    assertFalse(RevertResolver.isOutputStartWithRevertMethod(testABI));
    assertTrue(RevertResolver.isOutputStartWithRevertMethod(revertABI));
    assertFalse(RevertResolver.isOutputStartWithRevertMethod(testABI));
}
 
Example 8
Source File: RevertResolverTest.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void tryResolveRevertMessageTest() throws IOException {
    String revertMessage = "RevertMessage";
    Function revertFunction = newFunction("Error", revertMessage);
    String revertABI = FunctionEncoder.encode(revertFunction);

    Function testFunction = newFunction("testFunc", revertMessage);
    String testABI = FunctionEncoder.encode(testFunction);

    Tuple2<Boolean, String> booleanStringTuple2 =
            RevertResolver.tryResolveRevertMessage("", "");
    assertTrue(!booleanStringTuple2.getValue1());

    Tuple2<Boolean, String> booleanStringTuple20 =
            RevertResolver.tryResolveRevertMessage("0x0", revertABI);
    assertFalse(booleanStringTuple20.getValue1());

    Tuple2<Boolean, String> booleanStringTuple21 =
            RevertResolver.tryResolveRevertMessage("0x0", testABI);
    assertFalse(booleanStringTuple21.getValue1());

    Tuple2<Boolean, String> booleanStringTuple22 =
            RevertResolver.tryResolveRevertMessage("0x1", testABI);
    assertFalse(booleanStringTuple22.getValue1());

    Tuple2<Boolean, String> booleanStringTuple23 =
            RevertResolver.tryResolveRevertMessage("0x1", revertABI);
    assertTrue(booleanStringTuple23.getValue1());
    assertEquals(booleanStringTuple23.getValue2(), revertMessage);
}
 
Example 9
Source File: RevertResolverTest.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void tryResolveRevertMessageSMTest() throws IOException {
    EncryptType.setEncryptType(EncryptType.SM2_TYPE);
    String revertMessage = "RevertMessage";
    Function revertFunction = newFunction("Error", revertMessage);
    String revertABI = FunctionEncoder.encode(revertFunction);

    Function testFunction = newFunction("testFunc", revertMessage);
    String testABI = FunctionEncoder.encode(testFunction);

    Tuple2<Boolean, String> booleanStringTuple2 =
            RevertResolver.tryResolveRevertMessage("", "");
    assertFalse(booleanStringTuple2.getValue1());

    Tuple2<Boolean, String> booleanStringTuple20 =
            RevertResolver.tryResolveRevertMessage("0x0", revertABI);
    assertFalse(booleanStringTuple20.getValue1());

    Tuple2<Boolean, String> booleanStringTuple21 =
            RevertResolver.tryResolveRevertMessage("0x0", testABI);
    assertFalse(booleanStringTuple21.getValue1());

    Tuple2<Boolean, String> booleanStringTuple22 =
            RevertResolver.tryResolveRevertMessage("0x1", testABI);
    assertFalse(booleanStringTuple22.getValue1());

    Tuple2<Boolean, String> booleanStringTuple23 =
            RevertResolver.tryResolveRevertMessage("0x1", revertABI);
    assertTrue(booleanStringTuple23.getValue1());
    assertEquals(booleanStringTuple23.getValue2(), revertMessage);
    EncryptType.setEncryptType(EncryptType.ECDSA_TYPE);
}
 
Example 10
Source File: RevertResolverTest.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void tryResolveRevertMessageTest0() throws IOException {
    String revertMessage = "";
    Function revertFunction = newFunction("Error", revertMessage);
    String revertABI = FunctionEncoder.encode(revertFunction);

    Function testFunction = newFunction("testFunc", revertMessage);
    String testABI = FunctionEncoder.encode(testFunction);

    Tuple2<Boolean, String> booleanStringTuple2 =
            RevertResolver.tryResolveRevertMessage("", "");
    assertFalse(booleanStringTuple2.getValue1());

    Tuple2<Boolean, String> booleanStringTuple20 =
            RevertResolver.tryResolveRevertMessage("0x0", revertABI);
    assertFalse(booleanStringTuple20.getValue1());

    Tuple2<Boolean, String> booleanStringTuple21 =
            RevertResolver.tryResolveRevertMessage("0x0", testABI);
    assertFalse(booleanStringTuple21.getValue1());

    Tuple2<Boolean, String> booleanStringTuple22 =
            RevertResolver.tryResolveRevertMessage("0x1", testABI);
    assertFalse(booleanStringTuple22.getValue1());

    Tuple2<Boolean, String> booleanStringTuple23 =
            RevertResolver.tryResolveRevertMessage("0x1", revertABI);
    assertTrue(booleanStringTuple23.getValue1());
    assertEquals(booleanStringTuple23.getValue2(), revertMessage);
}
 
Example 11
Source File: RevertResolverTest.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void tryResolveRevertMessageSMTest0() throws IOException {
    EncryptType.setEncryptType(EncryptType.SM2_TYPE);
    String revertMessage = "";
    Function revertFunction = newFunction("Error", revertMessage);
    String revertABI = FunctionEncoder.encode(revertFunction);

    Function testFunction = newFunction("testFunc", revertMessage);
    String testABI = FunctionEncoder.encode(testFunction);

    Tuple2<Boolean, String> booleanStringTuple2 =
            RevertResolver.tryResolveRevertMessage("", "");
    assertFalse(booleanStringTuple2.getValue1());

    Tuple2<Boolean, String> booleanStringTuple20 =
            RevertResolver.tryResolveRevertMessage("0x0", revertABI);
    assertFalse(booleanStringTuple20.getValue1());

    Tuple2<Boolean, String> booleanStringTuple21 =
            RevertResolver.tryResolveRevertMessage("0x0", testABI);
    assertFalse(booleanStringTuple21.getValue1());

    Tuple2<Boolean, String> booleanStringTuple22 =
            RevertResolver.tryResolveRevertMessage("0x1", testABI);
    assertFalse(booleanStringTuple22.getValue1());

    Tuple2<Boolean, String> booleanStringTuple23 =
            RevertResolver.tryResolveRevertMessage("0x1", revertABI);
    assertTrue(booleanStringTuple23.getValue1());
    assertEquals(booleanStringTuple23.getValue2(), revertMessage);
    EncryptType.setEncryptType(EncryptType.ECDSA_TYPE);
}
 
Example 12
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 13
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);
    }
}
 
Example 14
Source File: TransService.java    From WeBASE-Transaction with Apache License 2.0 4 votes vote down vote up
/**
 * transaction send.
 * 
 * @param transInfoDto transaction info
 */
public void transSend(TransInfoDto transInfoDto) {
    log.debug("transSend transInfoDto:{}", JsonUtils.toJSONString(transInfoDto));
    Long id = transInfoDto.getId();
    log.info("transSend id:{}", id);
    int groupId = transInfoDto.getGroupId();
    int requestCount = transInfoDto.getRequestCount();
    int signType = transInfoDto.getSignType();
    try {
        // check status
        int status = transMapper.selectStatus(id, transInfoDto.getGmtCreate());
        if (status == 1) {
            log.debug("transSend id:{} has successed.", id);
            return;
        }
        // requestCount + 1
        transMapper.updateRequestCount(id, requestCount + 1, transInfoDto.getGmtCreate());
        // check requestCount
        if (requestCount == properties.getRequestCountMax()) {
            log.warn("transSend id:{} has reached limit:{}", id,
                    properties.getRequestCountMax());
            LogUtils.monitorAbnormalLogger().error(ConstantProperties.CODE_ABNORMAL_S0004,
                    ConstantProperties.MSG_ABNORMAL_S0004);
            return;
        }

        String contractAbi = transInfoDto.getContractAbi();
        String contractAddress = transInfoDto.getContractAddress();
        String funcName = transInfoDto.getFuncName();
        List<Object> params = JsonUtils.toJavaObjectList(transInfoDto.getFuncParam(), Object.class);

        // get function abi
        AbiDefinition abiDefinition = ContractAbiUtil.getAbiDefinition(funcName, contractAbi);
        // input format
        List<String> funcInputTypes = ContractAbiUtil.getFuncInputType(abiDefinition);
        List<Type> finalInputs = ContractAbiUtil.inputFormat(funcInputTypes, params);
        // 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);
        // data sign
        String signMsg = signMessage(groupId, signType, transInfoDto.getSignUserId(),
                contractAddress, encodedFunction);
        if (StringUtils.isBlank(signMsg)) {
            return;
        }
        // send transaction
        final CompletableFuture<TransactionReceipt> transFuture = new CompletableFuture<>();
        sendMessage(groupId, signMsg, transFuture);
        TransactionReceipt receipt =
                transFuture.get(properties.getTransMaxWait(), TimeUnit.SECONDS);
        transInfoDto.setTransHash(receipt.getTransactionHash());
        transInfoDto.setTransOutput(receipt.getOutput());
        transInfoDto.setReceiptStatus(receipt.isStatusOK());
        if (receipt.isStatusOK()) {
            transInfoDto.setHandleStatus(1);
        }
        transMapper.updateHandleStatus(transInfoDto);
    } catch (Exception e) {
        log.error("fail transSend id:{}", id, e);
        LogUtils.monitorAbnormalLogger().error(ConstantProperties.CODE_ABNORMAL_S0002,
                ConstantProperties.MSG_ABNORMAL_S0002);
    }
}