org.web3j.abi.FunctionReturnDecoder Java Examples

The following examples show how to use org.web3j.abi.FunctionReturnDecoder. 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: TokenRepository.java    From alpha-wallet-android with MIT License 6 votes vote down vote up
@Override
public Single<ContractLocator> getTokenResponse(String address, int chainId, String method)
{
    return Single.fromCallable(() -> {
        ContractLocator contractLocator = new ContractLocator(INVALID_CONTRACT, chainId);
        Function function = new Function(method,
                                                                 Arrays.<Type>asList(),
                                                                 Arrays.<TypeReference<?>>asList(new TypeReference<Utf8String>() {}));

        Wallet temp = new Wallet(null);
        String responseValue = callCustomNetSmartContractFunction(function, address, temp, chainId);
        if (responseValue == null) return contractLocator;

        List<Type> response = FunctionReturnDecoder.decode(
                responseValue, function.getOutputParameters());
        if (response.size() == 1)
        {
            return new ContractLocator((String) response.get(0).getValue(), chainId);
        }
        else
        {
            return contractLocator;
        }
    });
}
 
Example #3
Source File: Contract.java    From web3j with Apache License 2.0 6 votes vote down vote up
public static EventValues staticExtractEventParameters(Event event, Log log) {
    final 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 #4
Source File: EnsResolver.java    From alpha-wallet-android with MIT License 6 votes vote down vote up
private <T> T getContractData(int chainId, String address, Function function) throws Exception
{
    String responseValue = callSmartContractFunction(function, address, chainId);

    if (TextUtils.isEmpty(responseValue))
    {
        throw new Exception("Bad contract value");
    }
    else if (responseValue.equals("0x"))
    {
        return null;
    }

    List<Type> response = FunctionReturnDecoder.decode(
            responseValue, function.getOutputParameters());
    if (response.size() == 1)
    {
        return (T) response.get(0).getValue();
    }
    else
    {
        return null;
    }
}
 
Example #5
Source File: TokenRepository.java    From alpha-wallet-android with MIT License 6 votes vote down vote up
private String getName(String address, NetworkInfo network) throws Exception {
    Function function = nameOf();
    Wallet temp = new Wallet(null);
    String responseValue = callSmartContractFunction(function, address, network ,temp);

    if (TextUtils.isEmpty(responseValue)) return null;

    List<Type> response = FunctionReturnDecoder.decode(
            responseValue, function.getOutputParameters());
    if (response.size() == 1) {
        String name = (String)response.get(0).getValue();
        if (responseValue.length() > 2 && name.length() == 0)
        {
            name = checkBytesString(responseValue);
        }
        return name;
    } else {
        return null;
    }
}
 
Example #6
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 #7
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 #8
Source File: TransactionHandler.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
private <T> T callSmartContractAndGetResult(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 #9
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 #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: 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 #12
Source File: TokenRepository.java    From trust-wallet-android-source with GNU General Public License v3.0 5 votes vote down vote up
private BigDecimal getBalance(Wallet wallet, TokenInfo tokenInfo) throws Exception {
    org.web3j.abi.datatypes.Function function = balanceOf(wallet.address);
    String responseValue = callSmartContractFunction(function, tokenInfo.address, wallet);

    List<Type> response = FunctionReturnDecoder.decode(
            responseValue, function.getOutputParameters());
    if (response.size() == 1) {
        return new BigDecimal(((Uint256) response.get(0)).getValue());
    } else {
        return null;
    }
}
 
Example #13
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 #14
Source File: EthereumUtils.java    From jbpm-work-items with Apache License 2.0 5 votes vote down vote up
public static void observeContractEvent(Web3j web3j,
                                        String contractEventName,
                                        String contractAddress,
                                        List<TypeReference<?>> indexedParameters,
                                        List<TypeReference<?>> nonIndexedParameters,
                                        String eventReturnType,
                                        KieSession kieSession,
                                        String signalName,
                                        boolean doAbortOnUpdate,
                                        WorkItemManager workItemManager,
                                        WorkItem workItem) {

    Event event = new Event(contractEventName,
                            indexedParameters,
                            nonIndexedParameters);

    EthFilter filter = new EthFilter(DefaultBlockParameterName.EARLIEST,
                                     DefaultBlockParameterName.LATEST,
                                     contractAddress);

    filter.addSingleTopic(EventEncoder.encode(event));

    Class<Type> type = (Class<Type>) AbiTypes.getType(eventReturnType);
    TypeReference<Type> typeRef = TypeReference.create(type);

    web3j.ethLogObservable(filter).subscribe(
            eventTrigger -> {
                kieSession.signalEvent(signalName,
                                       FunctionReturnDecoder.decode(
                                               eventTrigger.getData(),
                                               Arrays.asList(typeRef)).get(0).getValue());
                if (doAbortOnUpdate) {
                    workItemManager.completeWorkItem(workItem.getId(),
                                                     null);
                }
            }
    );
}
 
Example #15
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 #16
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 #17
Source File: HumanStandardTokenIT.java    From web3j with Apache License 2.0 5 votes vote down vote up
private void confirmAllowance(
        String owner, String spender, String contractAddress, BigInteger expected)
        throws Exception {
    Function function = allowance(owner, spender);
    String responseValue = callSmartContractFunction(function, contractAddress);

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

    assertEquals(response.size(), (function.getOutputParameters().size()));
    assertEquals(response.get(0), (new Uint256(expected)));
}
 
Example #18
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 #19
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 #20
Source File: HumanStandardTokenIT.java    From web3j with Apache License 2.0 5 votes vote down vote up
public void sendTransferFromTransaction(
        Credentials credentials,
        String from,
        String to,
        BigInteger value,
        String contractAddress)
        throws Exception {

    Function function = transferFrom(from, to, 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);

    Event transferEvent = transferEvent();
    List<String> topics = log.getTopics();

    // 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(from)));
    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(value))));
}
 
Example #21
Source File: GreeterContractIT.java    From web3j with Apache License 2.0 5 votes vote down vote up
@Test
public void testGreeterContract() throws Exception {
    boolean accountUnlocked = unlockAccount();
    assertTrue(accountUnlocked);

    // create our smart contract
    String createTransactionHash = sendCreateContractTransaction();
    assertFalse(createTransactionHash.isEmpty());

    TransactionReceipt createTransactionReceipt =
            waitForTransactionReceipt(createTransactionHash);

    assertEquals(createTransactionReceipt.getTransactionHash(), (createTransactionHash));

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

    String contractAddress = createTransactionReceipt.getContractAddress();

    assertNotNull(contractAddress);

    // call our getter
    Function getFunction = createGreetFunction();
    String responseValue = callSmartContractFunction(getFunction, contractAddress);
    assertFalse(responseValue.isEmpty());

    List<Type> response =
            FunctionReturnDecoder.decode(responseValue, getFunction.getOutputParameters());
    assertEquals(response.size(), (1));
    assertEquals(response.get(0).getValue(), (VALUE));
}
 
Example #22
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 #23
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 #24
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 #25
Source File: TokenRepository.java    From ETHWallet with GNU General Public License v3.0 5 votes vote down vote up
private BigDecimal getBalance(Wallet wallet, TokenInfo tokenInfo) throws Exception {
    org.web3j.abi.datatypes.Function function = balanceOf(wallet.getAddress());
    String responseValue = callSmartContractFunction(function, tokenInfo.address, wallet);

    List<Type> response = FunctionReturnDecoder.decode(
            responseValue, function.getOutputParameters());
    if (response.size() == 1) {
        return new BigDecimal(((Uint256) response.get(0)).getValue());
    } else {
        return null;
    }
}
 
Example #26
Source File: TokenRepository.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
private BigDecimal getBalance(Wallet wallet, TokenInfo tokenInfo) throws Exception {
    Function function = balanceOf(wallet.address);
    NetworkInfo network = ethereumNetworkRepository.getNetworkByChain(tokenInfo.chainId);
    String responseValue = callSmartContractFunction(function, tokenInfo.address, network, wallet);

    if (responseValue == null) return BigDecimal.valueOf(-1); //early return for network error

    List<Type> response = FunctionReturnDecoder.decode(responseValue, function.getOutputParameters());
    if (response.size() == 1) {
        return new BigDecimal(((Uint256) response.get(0)).getValue());
    } else {
        return BigDecimal.ZERO;
    }
}
 
Example #27
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 #28
Source File: HumanStandardTokenIT.java    From etherscan-explorer with GNU General Public License v3.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());
    assertThat(response.size(), is(1));
    assertThat(response.get(0), equalTo(new Uint256(expected)));
}
 
Example #29
Source File: DefaultContractEventDetailsFactory.java    From eventeum with Apache License 2.0 5 votes vote down vote up
private List<Type> getIndexedParametersFromLog(ContractEventSpecification eventSpec, Log log) {
    if (isNullOrEmpty(eventSpec.getIndexedParameterDefinitions())) {
        return Collections.EMPTY_LIST;
    }

    final List<String> encodedParameters = log.getTopics().subList(1, log.getTopics().size());
    final List<ParameterDefinition> definitions = eventSpec.getIndexedParameterDefinitions();

    return IntStream.range(0, encodedParameters.size())
            .mapToObj(i -> FunctionReturnDecoder.decodeIndexedValue(encodedParameters.get(i),
                    Web3jUtil.getTypeReferenceFromParameterType(definitions.get(i).getType())))
            .collect(Collectors.toList());
}
 
Example #30
Source File: DefaultContractEventDetailsFactory.java    From eventeum with Apache License 2.0 5 votes vote down vote up
private List<Type> getNonIndexedParametersFromLog(ContractEventSpecification eventSpec, Log log) {
    if (isNullOrEmpty(eventSpec.getNonIndexedParameterDefinitions())) {
        return Collections.EMPTY_LIST;
    }

    return FunctionReturnDecoder.decode(
            log.getData(),
            Utils.convert(Web3jUtil.getTypeReferencesFromParameterDefinitions(
                    eventSpec.getNonIndexedParameterDefinitions())));
}