Java Code Examples for org.fisco.bcos.web3j.abi.FunctionReturnDecoder#decode()

The following examples show how to use org.fisco.bcos.web3j.abi.FunctionReturnDecoder#decode() . 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 vote down vote up
public static EventValues staticExtractEventParameters(Event event, Log log) {

        List<String> topics = log.getTopics();
        String encodedEventSignature = EventEncoder.encode(event);
        if (!topics.get(0).equals(encodedEventSignature)) {
            return null;
        }

        List<Type> indexedValues = new ArrayList<>();
        List<Type> nonIndexedValues =
                FunctionReturnDecoder.decode(log.getData(), event.getNonIndexedParameters());

        List<TypeReference<Type>> indexedParameters = event.getIndexedParameters();
        for (int i = 0; i < indexedParameters.size(); i++) {
            Type value =
                    FunctionReturnDecoder.decodeIndexedValue(
                            topics.get(i + 1), indexedParameters.get(i));
            indexedValues.add(value);
        }
        return new EventValues(indexedValues, nonIndexedValues);
    }
 
Example 2
Source File: Topic.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
public Tuple1<Boolean> getAddTopicACLOutput(TransactionReceipt transactionReceipt) {
    String data = transactionReceipt.getOutput();
    final Function function = new Function(FUNC_ADDTOPICACL, 
            Arrays.<Type>asList(), 
            Arrays.<TypeReference<?>>asList(new TypeReference<Bool>() {}));
    List<Type> results = FunctionReturnDecoder.decode(data, function.getOutputParameters());;
    return new Tuple1<Boolean>(

            (Boolean) results.get(0).getValue()
            );
}
 
Example 3
Source File: ChainGovernance.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
public Tuple1<BigInteger> getGrantOperatorOutput(TransactionReceipt transactionReceipt) {
    String data = transactionReceipt.getOutput();
    final Function function =
            new Function(
                    FUNC_GRANTOPERATOR,
                    Arrays.<Type>asList(),
                    Arrays.<TypeReference<?>>asList(new TypeReference<Int256>() {}));
    List<Type> results = FunctionReturnDecoder.decode(data, function.getOutputParameters());
    ;
    return new Tuple1<BigInteger>((BigInteger) results.get(0).getValue());
}
 
Example 4
Source File: ChainGovernance.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
public Tuple1<String> getRevokeOperatorInput(TransactionReceipt transactionReceipt) {
    String data = transactionReceipt.getInput().substring(10);
    final Function function =
            new Function(
                    FUNC_REVOKEOPERATOR,
                    Arrays.<Type>asList(),
                    Arrays.<TypeReference<?>>asList(new TypeReference<Address>() {}));
    List<Type> results = FunctionReturnDecoder.decode(data, function.getOutputParameters());
    ;
    return new Tuple1<String>((String) results.get(0).getValue());
}
 
Example 5
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 6
Source File: ContractLifeCyclePrecompiled.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
public Tuple1<BigInteger> getGrantManagerOutput(TransactionReceipt transactionReceipt) {
    String data = transactionReceipt.getOutput();
    final Function function =
            new Function(
                    FUNC_GRANTMANAGER,
                    Arrays.<Type>asList(),
                    Arrays.<TypeReference<?>>asList(new TypeReference<Int256>() {}));
    List<Type> results = FunctionReturnDecoder.decode(data, function.getOutputParameters());
    ;
    return new Tuple1<BigInteger>((BigInteger) results.get(0).getValue());
}
 
Example 7
Source File: TopicController.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
public Tuple8<List<String>, List<String>, List<BigInteger>, List<BigInteger>, List<BigInteger>, List<BigInteger>, List<BigInteger>, List<String>> getFlushTopicInfoInput(
    TransactionReceipt transactionReceipt) {
    String data = transactionReceipt.getInput().substring(10);
    final Function function = new Function(FUNC_FLUSHTOPICINFO, 
            Arrays.<Type>asList(), 
            Arrays.<TypeReference<?>>asList(
                new TypeReference<DynamicArray<Utf8String>>() {},
                new TypeReference<DynamicArray<Address>>() {},
                new TypeReference<DynamicArray<Uint256>>() {},
                new TypeReference<DynamicArray<Uint256>>() {},
                new TypeReference<DynamicArray<Uint256>>() {},
                new TypeReference<DynamicArray<Uint256>>() {},
                new TypeReference<DynamicArray<Uint256>>() {},
                new TypeReference<DynamicArray<Address>>() {}));
    List<Type> results = FunctionReturnDecoder.decode(data, function.getOutputParameters());;
    return new Tuple8<List<String>, List<String>, List<BigInteger>, List<BigInteger>, List<BigInteger>, List<BigInteger>, List<BigInteger>, List<String>>(

            convertToNative((List<Utf8String>) results.get(0).getValue()), 
            convertToNative((List<Address>) results.get(1).getValue()), 
            convertToNative((List<Uint256>) results.get(2).getValue()), 
            convertToNative((List<Uint256>) results.get(3).getValue()), 
            convertToNative((List<Uint256>) results.get(4).getValue()), 
            convertToNative((List<Uint256>) results.get(5).getValue()), 
            convertToNative((List<Uint256>) results.get(6).getValue()), 
            convertToNative((List<Address>) results.get(7).getValue())
            );
}
 
Example 8
Source File: BlockInfoServiceTest.java    From WeBASE-Collect-Bee with Apache License 2.0 5 votes vote down vote up
@Test
public void testInput() throws IOException {
    Block block = ethClient.getBlock(BigInteger.valueOf(8677));
    List<TransactionResult> transactionResults = block.getTransactions();
    log.info("transactionResults.size:{}", transactionResults.size());
    for (TransactionResult result : transactionResults) {
        BcosTransactionReceipt ethGetTransactionReceipt = web3j.getTransactionReceipt((String) result.get()).send();
        Optional<TransactionReceipt> opt = ethGetTransactionReceipt.getTransactionReceipt();
        if (opt.isPresent()) {
            log.info("TransactionReceipt hash: {}", opt.get().getTransactionHash());
            Optional<Transaction> optt =
                    web3j.getTransactionByHash(opt.get().getTransactionHash()).send().getTransaction();
            if (optt.isPresent()) {
                log.info("transaction hash : {}", optt.get().getHash());
                log.info("transaction info : {}", optt.get().getValue());
                List<Type> lt = new ArrayList<>();
                lt.add(Uint64.DEFAULT);
                List<TypeReference<?>> references = new ArrayList<>();
                TypeReference<Uint64> typeReference = new TypeReference<Uint64>() {
                };
                references.add(typeReference);
                List<TypeReference<Type>> ll = Utils.convert(references);
                List<Type> inputList = FunctionReturnDecoder.decode(optt.get().getInput(), ll);
                log.info("input : {}", inputList.size());
                log.info("input : {}", JacksonUtils.toJson(inputList));
            }

        }
    }

}
 
Example 9
Source File: FunctionTest.java    From WeBASE-Collect-Bee with Apache License 2.0 5 votes vote down vote up
public void testActivity() throws IOException, BaseException {
    BigInteger bigBlockHeight = new BigInteger(Integer.toString(200));
    Block block = ethClient.getBlock(bigBlockHeight);
    List<TransactionResult> transactionResults = block.getTransactions();
    log.info("transactionResults.size:{}", transactionResults.size());
    for (TransactionResult result : transactionResults) {
        BcosTransactionReceipt ethGetTransactionReceipt = web3j.getTransactionReceipt((String) result.get()).send();
        Optional<TransactionReceipt> opt = ethGetTransactionReceipt.getTransactionReceipt();
        if (opt.isPresent()) {
            log.info("TransactionReceipt hash: {}", opt.get().getTransactionHash());
            Optional<Transaction> optt =
                    web3j.getTransactionByHash(opt.get().getTransactionHash()).send().getTransaction();
            if (optt.isPresent()) {
                String rawInput = optt.get().getInput();
                log.info("input : {}", optt.get().getInput());
                List<TypeReference<Type>> referencesTypeList = new ArrayList<>(1);
                TypeReference exScore = TypeReferenceUtils.getTypeRef("uint64");
                referencesTypeList.add(exScore);

                List<Type> listT = FunctionReturnDecoder.decode(rawInput.substring(10), referencesTypeList);
                for (Type type : listT) {
                    log.info("type value : {}", type.getValue());
                }
                log.info("type info : {}", JacksonUtils.toJson(listT));
            }
        }
    }
}
 
Example 10
Source File: ContractLifeCyclePrecompiled.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
public Tuple1<BigInteger> getUnfreezeOutput(TransactionReceipt transactionReceipt) {
    String data = transactionReceipt.getOutput();
    final Function function =
            new Function(
                    FUNC_UNFREEZE,
                    Arrays.<Type>asList(),
                    Arrays.<TypeReference<?>>asList(new TypeReference<Int256>() {}));
    List<Type> results = FunctionReturnDecoder.decode(data, function.getOutputParameters());
    ;
    return new Tuple1<BigInteger>((BigInteger) results.get(0).getValue());
}
 
Example 11
Source File: ChainGovernance.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
public Tuple1<BigInteger> getUpdateThresholdOutput(TransactionReceipt transactionReceipt) {
    String data = transactionReceipt.getOutput();
    final Function function =
            new Function(
                    FUNC_UPDATETHRESHOLD,
                    Arrays.<Type>asList(),
                    Arrays.<TypeReference<?>>asList(new TypeReference<Int256>() {}));
    List<Type> results = FunctionReturnDecoder.decode(data, function.getOutputParameters());
    ;
    return new Tuple1<BigInteger>((BigInteger) results.get(0).getValue());
}
 
Example 12
Source File: RevertResolver.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
/**
 * @param status
 * @param output
 * @return
 */
public static Tuple2<Boolean, String> tryResolveRevertMessage(String status, String output) {
    if (!hasRevertMessage(status, output)) {
        return new Tuple2<>(false, null);
    }

    try {
        // 00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000030497373756572526f6c653a2063616c6c657220646f6573206e6f742068617665207468652049737375657220726f6c6500000000000000000000000000000000
        String rawOutput =
                Numeric.containsHexPrefix(output)
                        ? output.substring(RevertMethodWithHexPrefix.length())
                        : output.substring(RevertMethod.length());
        List<Type> result =
                FunctionReturnDecoder.decode(rawOutput, revertFunction.getOutputParameters());
        if (result.get(0) instanceof Utf8String) {
            String message = ((Utf8String) result.get(0)).getValue();
            if (logger.isDebugEnabled()) {
                logger.debug(" ABI: {} , RevertMessage: {}", output, message);
            }
            return new Tuple2<>(true, message);
        }
    } catch (Exception e) {
        logger.warn(" ABI: {}, e: {}", output, e);
    }

    return new Tuple2<>(false, null);
}
 
Example 13
Source File: Topic.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
public Tuple2<String, String> getAddTopicACLInput(TransactionReceipt transactionReceipt) {
    String data = transactionReceipt.getInput().substring(10);
    final Function function = new Function(FUNC_ADDTOPICACL, 
            Arrays.<Type>asList(), 
            Arrays.<TypeReference<?>>asList(new TypeReference<Utf8String>() {}, new TypeReference<Address>() {}));
    List<Type> results = FunctionReturnDecoder.decode(data, function.getOutputParameters());;
    return new Tuple2<String, String>(

            (String) results.get(0).getValue(), 
            (String) results.get(1).getValue()
            );
}
 
Example 14
Source File: Evidence.java    From WeBASE-Front with Apache License 2.0 5 votes vote down vote up
public Tuple3<BigInteger, byte[], byte[]> getAddSignaturesInput(TransactionReceipt transactionReceipt) {
    String data = transactionReceipt.getInput().substring(10);
    final Function function = new Function(FUNC_ADDSIGNATURES, 
            Arrays.<Type>asList(), 
            Arrays.<TypeReference<?>>asList(new TypeReference<Uint8>() {}, new TypeReference<Bytes32>() {}, new TypeReference<Bytes32>() {}));
    List<Type> results = FunctionReturnDecoder.decode(data, function.getOutputParameters());;
    return new Tuple3<BigInteger, byte[], byte[]>(

            (BigInteger) results.get(0).getValue(), 
            (byte[]) results.get(1).getValue(), 
            (byte[]) results.get(2).getValue()
            );
}
 
Example 15
Source File: CallContract.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
public List<Object> decode(String data, String retType) throws Exception {
    List<Object> result = new ArrayList<>();
    if (!retType.equals("") && data != null) {
        String types[] = retType.split(",");
        List<TypeReference<?>> references = getTypeReferenceList(types);

        List<Type> returns = FunctionReturnDecoder.decode(data, Utils.convert(references));

        result = types2Objects(returns, types);
    }
    return result;
}
 
Example 16
Source File: EvidenceSignersData.java    From WeBASE-Front with Apache License 2.0 5 votes vote down vote up
public Tuple1<String> getNewEvidenceOutput(TransactionReceipt transactionReceipt) {
    String data = transactionReceipt.getOutput();
    final Function function = new Function(FUNC_NEWEVIDENCE, 
            Arrays.<Type>asList(), 
            Arrays.<TypeReference<?>>asList(new TypeReference<Address>() {}));
    List<Type> results = FunctionReturnDecoder.decode(data, function.getOutputParameters());;
    return new Tuple1<String>(

            (String) results.get(0).getValue()
            );
}
 
Example 17
Source File: Topic.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
public Tuple1<BigInteger> getDelOperatorOutput(TransactionReceipt transactionReceipt) {
    String data = transactionReceipt.getOutput();
    final Function function = new Function(FUNC_DELOPERATOR, 
            Arrays.<Type>asList(), 
            Arrays.<TypeReference<?>>asList(new TypeReference<Uint256>() {}));
    List<Type> results = FunctionReturnDecoder.decode(data, function.getOutputParameters());;
    return new Tuple1<BigInteger>(

            (BigInteger) results.get(0).getValue()
            );
}
 
Example 18
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 19
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 20
Source File: CallContract.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
public List<Type> decode(String data, TypeReference<?>... typeReferences) {
    if (data.isEmpty() || data.equals("0x")) return null;
    List<TypeReference<?>> typeReferencesList = Arrays.<TypeReference<?>>asList(typeReferences);
    return FunctionReturnDecoder.decode(data, Utils.convert(typeReferencesList));
}