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

The following examples show how to use org.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 client-sdk-java with Apache License 2.0 7 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 == null || topics.size() == 0 || !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: Contract.java    From etherscan-explorer with GNU General Public License v3.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 3
Source File: Contract.java    From client-sdk-java 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);
    PlatonCall ethCall = web3j.platonCall(
            Transaction.createEthCallTransaction(
                    transactionManager.getFromAddress(), contractAddress, encodedFunction),
            defaultBlockParameter)
            .send();

    String value = ethCall.getValue();
    return FunctionReturnDecoder.decode(value, function.getOutputParameters());
}
 
Example 4
Source File: EthereumUtils.java    From jbpm-work-items with Apache License 2.0 5 votes vote down vote up
public static Object queryExistingContract(Credentials credentials,
                                           Web3j web3j,
                                           String contractAddress,
                                           String contractMethodName,
                                           List<Type> contractMethodInputTypes,
                                           List<TypeReference<?>> contractMethodOutputTypes
) throws Exception {

    Function function = getFunction(contractMethodName,
                                    contractMethodInputTypes,
                                    contractMethodOutputTypes);

    Transaction transaction = Transaction.createEthCallTransaction(credentials.getAddress(),
                                                                   contractAddress,
                                                                   getEncodedFunction(function));

    EthCall response = web3j.ethCall(
            transaction,
            DefaultBlockParameterName.LATEST).sendAsync().get();

    List<Type> responseTypeList = FunctionReturnDecoder.decode(
            response.getValue(),
            function.getOutputParameters());

    if (responseTypeList != null && responseTypeList.size() > 0) {
        return responseTypeList.get(0).getValue();
    } else {
        return null;
    }
}
 
Example 5
Source File: HumanStandardTokenIT.java    From web3j with Apache License 2.0 5 votes vote down vote up
private void confirmBalance(String address, String contractAddress, BigInteger expected)
        throws Exception {
    Function function = balanceOf(address);
    String responseValue = callSmartContractFunction(function, contractAddress);

    List<Type> response =
            FunctionReturnDecoder.decode(responseValue, function.getOutputParameters());
    assertEquals(response.size(), (1));
    assertEquals(response.get(0), (new Uint256(expected)));
}
 
Example 6
Source File: HumanStandardTokenIT.java    From web3j with Apache License 2.0 5 votes vote down vote up
private void sendApproveTransaction(
        Credentials credentials, String spender, BigInteger value, String contractAddress)
        throws Exception {
    Function function = approve(spender, value);
    String functionHash = execute(credentials, function, contractAddress);

    TransactionReceipt transferTransactionReceipt = waitForTransactionReceipt(functionHash);
    assertEquals(transferTransactionReceipt.getTransactionHash(), (functionHash));

    List<Log> logs = transferTransactionReceipt.getLogs();
    assertFalse(logs.isEmpty());
    Log log = logs.get(0);

    // verify the event was called with the function parameters
    List<String> topics = log.getTopics();
    assertEquals(topics.size(), (3));

    // event Transfer(address indexed _from, address indexed _to, uint256 _value);
    Event event = approvalEvent();

    // check function signature - we only have a single topic our event signature,
    // there are no indexed parameters in this example
    String encodedEventSignature = EventEncoder.encode(event);
    assertEquals(topics.get(0), (encodedEventSignature));
    assertEquals(new Address(topics.get(1)), (new Address(credentials.getAddress())));
    assertEquals(new Address(topics.get(2)), (new Address(spender)));

    // verify our two event parameters
    List<Type> results =
            FunctionReturnDecoder.decode(log.getData(), event.getNonIndexedParameters());
    assertEquals(results, (Collections.singletonList(new Uint256(value))));
}
 
Example 7
Source File: EthCall.java    From web3j with Apache License 2.0 5 votes vote down vote up
public String getRevertReason() {
    if (isErrorInResult()) {
        String hexRevertReason = getValue().substring(errorMethodId.length());
        List<Type> decoded = FunctionReturnDecoder.decode(hexRevertReason, revertReasonType);
        Utf8String decodedRevertReason = (Utf8String) decoded.get(0);
        return decodedRevertReason.getValue();
    } else if (hasError()) {
        return getError().getMessage();
    }
    return null;
}
 
Example 8
Source File: TransactionHandler.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
private List callSmartContractFunctionArray(
        org.web3j.abi.datatypes.Function function, String contractAddress, String address) throws Exception
{
    String encodedFunction = FunctionEncoder.encode(function);
    String value = makeEthCall(
            org.web3j.protocol.core.methods.request.Transaction
                    .createEthCallTransaction(address, contractAddress, encodedFunction));

    List<Type> values = FunctionReturnDecoder.decode(value, function.getOutputParameters());
    if (values.isEmpty()) return null;

    Type T = values.get(0);
    Object o = T.getValue();
    return (List) o;
}
 
Example 9
Source File: Contract.java    From web3j 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);

    String value = call(contractAddress, encodedFunction, defaultBlockParameter);

    return FunctionReturnDecoder.decode(value, function.getOutputParameters());
}
 
Example 10
Source File: TransactionHandler.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
private <T> T getContractData(String address, org.web3j.abi.datatypes.Function function) throws Exception
{
    String responseValue = callSmartContractFunction(function, address);

    List<Type> response = FunctionReturnDecoder.decode(
            responseValue, function.getOutputParameters());
    if (response.size() == 1)
    {
        return (T) response.get(0).getValue();
    }
    else
    {
        return null;
    }
}
 
Example 11
Source File: HumanStandardTokenIT.java    From web3j with Apache License 2.0 5 votes vote down vote up
private void sendTransferTokensTransaction(
        Credentials credentials, String to, String contractAddress, BigInteger qty)
        throws Exception {

    Function function = transfer(to, qty);
    String functionHash = execute(credentials, function, contractAddress);

    TransactionReceipt transferTransactionReceipt = waitForTransactionReceipt(functionHash);
    assertEquals(transferTransactionReceipt.getTransactionHash(), (functionHash));

    List<Log> logs = transferTransactionReceipt.getLogs();
    assertFalse(logs.isEmpty());
    Log log = logs.get(0);

    // verify the event was called with the function parameters
    List<String> topics = log.getTopics();
    assertEquals(topics.size(), (3));

    Event transferEvent = transferEvent();

    // check function signature - we only have a single topic our event signature,
    // there are no indexed parameters in this example
    String encodedEventSignature = EventEncoder.encode(transferEvent);
    assertEquals(topics.get(0), (encodedEventSignature));
    assertEquals(new Address(topics.get(1)), (new Address(credentials.getAddress())));
    assertEquals(new Address(topics.get(2)), (new Address(to)));

    // verify qty transferred
    List<Type> results =
            FunctionReturnDecoder.decode(
                    log.getData(), transferEvent.getNonIndexedParameters());
    assertEquals(results, (Collections.singletonList(new Uint256(qty))));
}
 
Example 12
Source File: HumanStandardTokenIT.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
private void sendTransferTokensTransaction(
        Credentials credentials, String to, String contractAddress, BigInteger qty)
        throws Exception {

    Function function = transfer(to, qty);
    String functionHash = execute(credentials, function, contractAddress);

    TransactionReceipt transferTransactionReceipt =
            waitForTransactionReceipt(functionHash);
    assertThat(transferTransactionReceipt.getTransactionHash(), is(functionHash));

    List<Log> logs = transferTransactionReceipt.getLogs();
    assertFalse(logs.isEmpty());
    Log log = logs.get(0);

    // verify the event was called with the function parameters
    List<String> topics = log.getTopics();
    assertThat(topics.size(), is(3));

    Event transferEvent = transferEvent();

    // check function signature - we only have a single topic our event signature,
    // there are no indexed parameters in this example
    String encodedEventSignature = EventEncoder.encode(transferEvent);
    assertThat(topics.get(0), is(encodedEventSignature));
    assertThat(new Address(topics.get(1)), is(new Address(credentials.getAddress())));
    assertThat(new Address(topics.get(2)), is(new Address(to)));

    // verify qty transferred
    List<Type> results = FunctionReturnDecoder.decode(
            log.getData(), transferEvent.getNonIndexedParameters());
    assertThat(results, equalTo(Collections.singletonList(new Uint256(qty))));
}
 
Example 13
Source File: TransactionHandler.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
private List callSmartContractFunctionArray(
        org.web3j.abi.datatypes.Function function, String contractAddress, String address) throws Exception
{
    String encodedFunction = FunctionEncoder.encode(function);
    String value = makeEthCall(
            org.web3j.protocol.core.methods.request.Transaction
                    .createEthCallTransaction(address, contractAddress, encodedFunction));

    List<Type> values = FunctionReturnDecoder.decode(value, function.getOutputParameters());
    if (values.isEmpty()) return null;

    Type T = values.get(0);
    Object o = T.getValue();
    return (List) o;
}
 
Example 14
Source File: HumanStandardTokenIT.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
private BigInteger getTotalSupply(String contractAddress) throws Exception {
    Function function = totalSupply();
    String responseValue = callSmartContractFunction(function, contractAddress);

    List<Type> response = FunctionReturnDecoder.decode(
            responseValue, function.getOutputParameters());

    assertThat(response.size(), is(1));
    return (BigInteger) response.get(0).getValue();
}
 
Example 15
Source File: HumanStandardTokenIT.java    From web3j with Apache License 2.0 5 votes vote down vote up
private BigInteger getTotalSupply(String contractAddress) throws Exception {
    Function function = totalSupply();
    String responseValue = callSmartContractFunction(function, contractAddress);

    List<Type> response =
            FunctionReturnDecoder.decode(responseValue, function.getOutputParameters());

    assertEquals(response.size(), (1));
    return (BigInteger) response.get(0).getValue();
}
 
Example 16
Source File: TokenRepository.java    From Upchain-wallet with GNU Affero General Public License v3.0 5 votes vote down vote up
private BigDecimal getBalance(String walletAddress, TokenInfo tokenInfo) throws Exception {
    org.web3j.abi.datatypes.Function function = balanceOf(walletAddress);
    String responseValue = callSmartContractFunction(function, tokenInfo.address, walletAddress);

    List<Type> response = FunctionReturnDecoder.decode(
            responseValue, function.getOutputParameters());
    if (response.size() == 1) {
        return new BigDecimal(((Uint256) response.get(0)).getValue());
    } else {
        return null;
    }
}
 
Example 17
Source File: EventFilterIT.java    From etherscan-explorer with GNU General Public License v3.0 4 votes vote down vote up
@Test
public void testEventFilter() throws Exception {
    unlockAccount();

    Function function = createFibonacciFunction();
    String encodedFunction = FunctionEncoder.encode(function);

    BigInteger gas = estimateGas(encodedFunction);
    String transactionHash = sendTransaction(ALICE, CONTRACT_ADDRESS, gas, encodedFunction);

    TransactionReceipt transactionReceipt =
            waitForTransactionReceipt(transactionHash);

    assertFalse("Transaction execution ran out of gas",
            gas.equals(transactionReceipt.getGasUsed()));

    List<Log> logs = transactionReceipt.getLogs();
    assertFalse(logs.isEmpty());

    Log log = logs.get(0);

    List<String> topics = log.getTopics();
    assertThat(topics.size(), is(1));

    Event event = new Event("Notify",
            Collections.emptyList(),
            Arrays.asList(new TypeReference<Uint256>() {}, new TypeReference<Uint256>() {}));

    // check function signature - we only have a single topic our event signature,
    // there are no indexed parameters in this example
    String encodedEventSignature = EventEncoder.encode(event);
    assertThat(topics.get(0),
            is(encodedEventSignature));

    // verify our two event parameters
    List<Type> results = FunctionReturnDecoder.decode(
            log.getData(), event.getNonIndexedParameters());
    assertThat(results, equalTo(Arrays.asList(
            new Uint256(BigInteger.valueOf(7)), new Uint256(BigInteger.valueOf(13)))));

    // finally check it shows up in the event filter
    List<EthLog.LogResult> filterLogs = createFilterForEvent(
            encodedEventSignature, CONTRACT_ADDRESS);
    assertFalse(filterLogs.isEmpty());
}
 
Example 18
Source File: EventFilterIT.java    From web3j with Apache License 2.0 4 votes vote down vote up
@Test
public void testEventFilter() throws Exception {
    unlockAccount();

    Function function = createFibonacciFunction();
    String encodedFunction = FunctionEncoder.encode(function);

    BigInteger gas = estimateGas(encodedFunction);
    String transactionHash = sendTransaction(ALICE, CONTRACT_ADDRESS, gas, encodedFunction);

    TransactionReceipt transactionReceipt = waitForTransactionReceipt(transactionHash);

    assertFalse(gas.equals(transactionReceipt.getGasUsed()));

    List<Log> logs = transactionReceipt.getLogs();
    assertFalse(logs.isEmpty());

    Log log = logs.get(0);

    List<String> topics = log.getTopics();
    assertEquals(topics.size(), (1));

    Event event =
            new Event(
                    "Notify",
                    Arrays.asList(
                            new TypeReference<Uint256>() {}, new TypeReference<Uint256>() {}));

    // check function signature - we only have a single topic our event signature,
    // there are no indexed parameters in this example
    String encodedEventSignature = EventEncoder.encode(event);
    assertEquals(topics.get(0), (encodedEventSignature));

    // verify our two event parameters
    List<Type> results =
            FunctionReturnDecoder.decode(log.getData(), event.getNonIndexedParameters());
    assertEquals(
            results,
            (Arrays.asList(
                    new Uint256(BigInteger.valueOf(7)), new Uint256(BigInteger.valueOf(13)))));

    // finally check it shows up in the event filter
    List<EthLog.LogResult> filterLogs =
            createFilterForEvent(encodedEventSignature, CONTRACT_ADDRESS);
    assertFalse(filterLogs.isEmpty());
}
 
Example 19
Source File: TokenscriptFunction.java    From alpha-wallet-android with MIT License 4 votes vote down vote up
private String handleTransactionResult(TransactionResult result, Function function, String responseValue, Attribute attr, long lastTransactionTime)
{
    String transResult = null;
    try
    {
        //try to interpret the value. For now, just use the raw return value - this is more reliable until we need to interpret arrays
        List<Type> response = FunctionReturnDecoder.decode(responseValue, function.getOutputParameters());
        if (response.size() > 0)
        {
            result.resultTime = lastTransactionTime;
            Type val = response.get(0);

            BigInteger value;
            byte[] bytes = Bytes.trimLeadingZeroes(Numeric.hexStringToByteArray(responseValue));
            String hexBytes = Numeric.toHexString(bytes);

            switch (attr.syntax)
            {
                case Boolean:
                    value = Numeric.toBigInt(hexBytes);
                    transResult = value.equals(BigDecimal.ZERO) ? "FALSE" : "TRUE";
                    break;
                case Integer:
                    value = Numeric.toBigInt(hexBytes);
                    transResult = value.toString();
                    break;
                case BitString:
                case NumericString:
                    if (val.getTypeAsString().equals("string"))
                    {
                        transResult = (String)val.getValue();
                        if (responseValue.length() > 2 && transResult.length() == 0)
                        {
                            transResult = checkBytesString(responseValue);
                        }
                    }
                    else
                    {
                        //should be a decimal string
                        value = Numeric.toBigInt(hexBytes);
                        transResult = value.toString();
                    }
                    break;
                case IA5String:
                case DirectoryString:
                case GeneralizedTime:
                case CountryString:
                    if (val.getTypeAsString().equals("string"))
                    {
                        transResult = (String)val.getValue();
                        if (responseValue.length() > 2 && transResult.length() == 0)
                        {
                            transResult = checkBytesString(responseValue);
                        }
                    }
                    else if (val.getTypeAsString().equals("address"))
                    {
                        transResult = (String)val.getValue();
                    }
                    else
                    {
                        transResult = hexBytes;
                    }
                    break;
                default:
                    transResult = hexBytes;
                    break;
            }
        }
        else
        {
            result.resultTime = lastTransactionTime == -1 ? -1 : 0;
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

    return transResult;
}
 
Example 20
Source File: DeployContractIT.java    From web3j with Apache License 2.0 3 votes vote down vote up
@Test
public void testContractCreation() throws Exception {
    boolean accountUnlocked = unlockAccount();
    assertTrue(accountUnlocked);

    String transactionHash = sendTransaction();
    assertFalse(transactionHash.isEmpty());

    TransactionReceipt transactionReceipt = waitForTransactionReceipt(transactionHash);

    assertEquals(transactionReceipt.getTransactionHash(), (transactionHash));

    assertFalse(transactionReceipt.getGasUsed().equals(GAS_LIMIT));

    String contractAddress = transactionReceipt.getContractAddress();

    assertNotNull(contractAddress);

    Function function = createFibonacciFunction();

    String responseValue = callSmartContractFunction(function, contractAddress);
    assertFalse(responseValue.isEmpty());

    List<Type> uint =
            FunctionReturnDecoder.decode(responseValue, function.getOutputParameters());
    assertEquals(uint.size(), (1));
    assertEquals(uint.get(0).getValue(), (BigInteger.valueOf(13)));
}