org.web3j.abi.datatypes.Function Java Examples

The following examples show how to use org.web3j.abi.datatypes.Function. 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 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected <T extends Type, R> R executeCallSingleValueReturn(
        Function function, Class<R> returnType) throws IOException {
    T result = executeCallSingleValueReturn(function);
    if (result == null) {
        throw new ContractCallException("Empty value (0x) returned from contract");
    }

    Object value = result.getValue();
    if (returnType.isAssignableFrom(value.getClass())) {
        return (R) value;
    } else if (result.getClass().equals(Address.class) && returnType.equals(String.class)) {
        return (R) result.toString();  // cast isn't necessary
    } else {
        throw new ContractCallException(
                "Unable to convert response: " + value
                        + " to expected type: " + returnType.getSimpleName());
    }
}
 
Example #2
Source File: PublicResolver.java    From web3j with Apache License 2.0 6 votes vote down vote up
public RemoteCall<Tuple2<BigInteger, byte[]>> ABI(byte[] node, BigInteger contentTypes) {
    final Function function = new Function(FUNC_ABI, 
            Arrays.<Type>asList(new org.web3j.abi.datatypes.generated.Bytes32(node), 
            new org.web3j.abi.datatypes.generated.Uint256(contentTypes)), 
            Arrays.<TypeReference<?>>asList(new TypeReference<Uint256>() {}, new TypeReference<DynamicBytes>() {}));
    return new RemoteCall<Tuple2<BigInteger, byte[]>>(
            new Callable<Tuple2<BigInteger, byte[]>>() {
                @Override
                public Tuple2<BigInteger, byte[]> call() throws Exception {
                    List<Type> results = executeCallMultipleValueReturn(function);
                    return new Tuple2<BigInteger, byte[]>(
                            (BigInteger) results.get(0).getValue(), 
                            (byte[]) results.get(1).getValue());
                }
            });
}
 
Example #3
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 #4
Source File: FunctionReturnDecoderTest.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleFunctionStringResultDecode() {
    Function function = new Function("simple",
            Arrays.asList(),
            Collections.singletonList(new TypeReference<Utf8String>() {
            }));

    List<Type> utf8Strings = FunctionReturnDecoder.decode(

            "0x0000000000000000000000000000000000000000000000000000000000000020"
                    + "000000000000000000000000000000000000000000000000000000000000000d"
                    + "6f6e65206d6f72652074696d6500000000000000000000000000000000000000",
            function.getOutputParameters());

    assertThat(utf8Strings.get(0).getValue(), is("one more time"));
}
 
Example #5
Source File: Arrays.java    From web3j with Apache License 2.0 6 votes vote down vote up
public RemoteFunctionCall<List> multiDynamic(List<List<BigInteger>> input) {
    final Function function = new Function(FUNC_MULTIDYNAMIC, 
            java.util.Arrays.<Type>asList(new org.web3j.abi.datatypes.DynamicArray<org.web3j.abi.datatypes.generated.StaticArray2>(
                    org.web3j.abi.datatypes.generated.StaticArray2.class,
                    org.web3j.abi.Utils.typeMap(input, org.web3j.abi.datatypes.generated.StaticArray2.class,
            org.web3j.abi.datatypes.generated.Uint256.class))), 
            java.util.Arrays.<TypeReference<?>>asList(new TypeReference<DynamicArray<Uint256>>() {}));
    return new RemoteFunctionCall<List>(function,
            new Callable<List>() {
                @Override
                @SuppressWarnings("unchecked")
                public List call() throws Exception {
                    List<Type> result = (List<Type>) executeCallSingleValueReturn(function, List.class);
                    return convertToNative(result);
                }
            });
}
 
Example #6
Source File: Ballot.java    From web3j with Apache License 2.0 6 votes vote down vote up
public RemoteCall<Tuple4<BigInteger, Boolean, String, BigInteger>> voters(String param0) {
    final Function function = new Function(FUNC_VOTERS,
            Arrays.<Type>asList(new org.web3j.abi.datatypes.Address(param0)),
            Arrays.<TypeReference<?>>asList(new TypeReference<Uint256>() {}, new TypeReference<Bool>() {}, new TypeReference<Address>() {}, new TypeReference<Uint256>() {}));
    return new RemoteCall<Tuple4<BigInteger, Boolean, String, BigInteger>>(
            new Callable<Tuple4<BigInteger, Boolean, String, BigInteger>>() {
                @Override
                public Tuple4<BigInteger, Boolean, String, BigInteger> call() throws Exception {
                    List<Type> results = executeCallMultipleValueReturn(function);
                    return new Tuple4<BigInteger, Boolean, String, BigInteger>(
                            (BigInteger) results.get(0).getValue(),
                            (Boolean) results.get(1).getValue(),
                            (String) results.get(2).getValue(),
                            (BigInteger) results.get(3).getValue());
                }
            });
}
 
Example #7
Source File: Arrays.java    From web3j with Apache License 2.0 6 votes vote down vote up
public RemoteFunctionCall<List> multiFixed(List<List<BigInteger>> input) {
    final Function function = new Function(FUNC_MULTIFIXED, 
            java.util.Arrays.<Type>asList(new org.web3j.abi.datatypes.generated.StaticArray6<org.web3j.abi.datatypes.generated.StaticArray2>(
                    org.web3j.abi.datatypes.generated.StaticArray2.class,
                    org.web3j.abi.Utils.typeMap(input, org.web3j.abi.datatypes.generated.StaticArray2.class,
            org.web3j.abi.datatypes.generated.Uint256.class))), 
            java.util.Arrays.<TypeReference<?>>asList(new TypeReference<DynamicArray<Uint256>>() {}));
    return new RemoteFunctionCall<List>(function,
            new Callable<List>() {
                @Override
                @SuppressWarnings("unchecked")
                public List call() throws Exception {
                    List<Type> result = (List<Type>) executeCallSingleValueReturn(function, List.class);
                    return convertToNative(result);
                }
            });
}
 
Example #8
Source File: TokenRepository.java    From alpha-wallet-android with MIT License 6 votes vote down vote up
public static byte[] createDropCurrency(MagicLinkData order, int v, byte[] r, byte[] s, String recipient)
{
    Function function = new Function(
            "dropCurrency",
            Arrays.asList(new org.web3j.abi.datatypes.generated.Uint32(order.nonce),
                          new org.web3j.abi.datatypes.generated.Uint32(order.amount),
                          new org.web3j.abi.datatypes.generated.Uint32(order.expiry),
                          new org.web3j.abi.datatypes.generated.Uint8(v),
                          new org.web3j.abi.datatypes.generated.Bytes32(r),
                          new org.web3j.abi.datatypes.generated.Bytes32(s),
                          new org.web3j.abi.datatypes.Address(recipient)),
            Collections.emptyList());

    String encodedFunction = FunctionEncoder.encode(function);
    return Numeric.hexStringToByteArray(Numeric.cleanHexPrefix(encodedFunction));
}
 
Example #9
Source File: EventEmitter.java    From eventeum with Apache License 2.0 6 votes vote down vote up
public Flowable<DummyEventAdditionalTypesEventResponse> dummyEventAdditionalTypesEventFlowable(EthFilter filter) {
    return web3j.ethLogFlowable(filter).map(new io.reactivex.functions.Function<Log, DummyEventAdditionalTypesEventResponse>() {
        @Override
        public DummyEventAdditionalTypesEventResponse apply(Log log) {
            Contract.EventValuesWithLog eventValues = extractEventParametersWithLog(DUMMYEVENTADDITIONALTYPES_EVENT, log);
            DummyEventAdditionalTypesEventResponse typedResponse = new DummyEventAdditionalTypesEventResponse();
            typedResponse.log = log;
            typedResponse.uint16Value = (BigInteger) eventValues.getIndexedValues().get(0).getValue();
            typedResponse.int64Value = (BigInteger) eventValues.getIndexedValues().get(1).getValue();
            typedResponse.addressArray = (List<String>) eventValues.getNonIndexedValues().get(0).getValue();
            typedResponse.byteValue = (byte[]) eventValues.getNonIndexedValues().get(1).getValue();
            typedResponse.boolValue = (Boolean) eventValues.getNonIndexedValues().get(2).getValue();
            return typedResponse;
        }
    });
}
 
Example #10
Source File: ERC721.java    From web3j with Apache License 2.0 5 votes vote down vote up
public Flowable<ApprovalForAllEventResponse> approvalForAllEventFlowable(EthFilter filter) {
    return web3j.ethLogFlowable(filter).map(new io.reactivex.functions.Function<Log, ApprovalForAllEventResponse>() {
        @Override
        public ApprovalForAllEventResponse apply(Log log) {
            Contract.EventValuesWithLog eventValues = extractEventParametersWithLog(APPROVALFORALL_EVENT, log);
            ApprovalForAllEventResponse typedResponse = new ApprovalForAllEventResponse();
            typedResponse.log = log;
            typedResponse._owner = (String) eventValues.getIndexedValues().get(0).getValue();
            typedResponse._operator = (String) eventValues.getIndexedValues().get(1).getValue();
            typedResponse._approved = (Boolean) eventValues.getNonIndexedValues().get(0).getValue();
            return typedResponse;
        }
    });
}
 
Example #11
Source File: FunctionReturnDecoderTest.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testMultipleResultFunctionDecode() {
    Function function = new Function(
            "test",
            Collections.<Type>emptyList(),
            Arrays.asList(new TypeReference<Uint>() { }, new TypeReference<Uint>() { })
    );

    assertThat(FunctionReturnDecoder.decode(
            "0x0000000000000000000000000000000000000000000000000000000000000037"
            + "0000000000000000000000000000000000000000000000000000000000000007",
            function.getOutputParameters()),
            equalTo(Arrays.asList(new Uint(BigInteger.valueOf(55)),
                    new Uint(BigInteger.valueOf(7)))));
}
 
Example #12
Source File: SimpleAuction.java    From web3j with Apache License 2.0 5 votes vote down vote up
public Flowable<HighestBidIncreasedEventResponse> highestBidIncreasedEventFlowable(EthFilter filter) {
    return web3j.ethLogFlowable(filter).map(new io.reactivex.functions.Function<Log, HighestBidIncreasedEventResponse>() {
        @Override
        public HighestBidIncreasedEventResponse apply(Log log) {
            Contract.EventValuesWithLog eventValues = extractEventParametersWithLog(HIGHESTBIDINCREASED_EVENT, log);
            HighestBidIncreasedEventResponse typedResponse = new HighestBidIncreasedEventResponse();
            typedResponse.log = log;
            typedResponse.bidder = (String) eventValues.getNonIndexedValues().get(0).getValue();
            typedResponse.amount = (BigInteger) eventValues.getNonIndexedValues().get(1).getValue();
            return typedResponse;
        }
    });
}
 
Example #13
Source File: ENS.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
public RemoteCall<TransactionReceipt> setOwner(byte[] node, String owner) {
    Function function = new Function(
            "setOwner",
            Arrays.<Type>asList(new org.web3j.abi.datatypes.generated.Bytes32(node),
            new org.web3j.abi.datatypes.Address(owner)),
            Collections.<TypeReference<?>>emptyList());
    return executeRemoteCallTransaction(function);
}
 
Example #14
Source File: PublicResolver.java    From web3j with Apache License 2.0 5 votes vote down vote up
public Flowable<PubkeyChangedEventResponse> pubkeyChangedEventFlowable(EthFilter filter) {
    return web3j.ethLogFlowable(filter).map(new io.reactivex.functions.Function<Log, PubkeyChangedEventResponse>() {
        @Override
        public PubkeyChangedEventResponse apply(Log log) {
            Contract.EventValuesWithLog eventValues = extractEventParametersWithLog(PUBKEYCHANGED_EVENT, log);
            PubkeyChangedEventResponse typedResponse = new PubkeyChangedEventResponse();
            typedResponse.log = log;
            typedResponse.node = (byte[]) eventValues.getIndexedValues().get(0).getValue();
            typedResponse.x = (byte[]) eventValues.getNonIndexedValues().get(0).getValue();
            typedResponse.y = (byte[]) eventValues.getNonIndexedValues().get(1).getValue();
            return typedResponse;
        }
    });
}
 
Example #15
Source File: HumanStandardTokenIT.java    From etherscan-explorer with GNU General Public License v3.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);
    assertThat(transferTransactionReceipt.getTransactionHash(), is(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);
    assertThat(topics.get(0), is(encodedEventSignature));
    assertThat(new Address(topics.get(1)), is(new Address(from)));
    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(value))));
}
 
Example #16
Source File: ERC721Ticket.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
public Function getPassToFunction(BigInteger expiry, List<BigInteger> tokenIds, int v, byte[] r, byte[] s, String recipient)
{
    return new Function(
            "passTo",
            Arrays.asList(new org.web3j.abi.datatypes.generated.Uint256(expiry),
                          getDynArray(tokenIds),
                          new org.web3j.abi.datatypes.generated.Uint8(v),
                          new org.web3j.abi.datatypes.generated.Bytes32(r),
                          new org.web3j.abi.datatypes.generated.Bytes32(s),
                          new org.web3j.abi.datatypes.Address(recipient)),
            Collections.emptyList());
}
 
Example #17
Source File: EthCallIT.java    From web3j with Apache License 2.0 5 votes vote down vote up
private EthCall ethCall(BigInteger value) throws java.io.IOException {
    final Function function =
            new Function(
                    Revert.FUNC_SET,
                    Collections.singletonList(new Uint256(value)),
                    Collections.emptyList());
    String encodedFunction = FunctionEncoder.encode(function);

    return web3j.ethCall(
                    Transaction.createEthCallTransaction(
                            ALICE.getAddress(), contract.getContractAddress(), encodedFunction),
                    DefaultBlockParameterName.LATEST)
            .send();
}
 
Example #18
Source File: FunctionReturnDecoderTest.java    From web3j with Apache License 2.0 5 votes vote down vote up
@Test
public void testSimpleFunctionDecode() {
    Function function =
            new Function(
                    "test",
                    Collections.<Type>emptyList(),
                    Collections.singletonList(new TypeReference<Uint>() {}));

    assertEquals(
            FunctionReturnDecoder.decode(
                    "0x0000000000000000000000000000000000000000000000000000000000000037",
                    function.getOutputParameters()),
            (Collections.singletonList(new Uint(BigInteger.valueOf(55)))));
}
 
Example #19
Source File: HumanStandardToken.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
public RemoteCall<BigInteger> allowance(String _owner, String _spender) {
    final Function function = new Function("allowance", 
            Arrays.<Type>asList(new org.web3j.abi.datatypes.Address(_owner), 
            new org.web3j.abi.datatypes.Address(_spender)), 
            Arrays.<TypeReference<?>>asList(new TypeReference<Uint256>() {}));
    return executeRemoteCallSingleValueReturn(function, BigInteger.class);
}
 
Example #20
Source File: TokenERC20.java    From Android-Wallet-Token-ERC20 with Apache License 2.0 5 votes vote down vote up
public RemoteCall<BigInteger> allowance(String param0, String param1) {
    Function function = new Function("allowance",
            Arrays.<Type>asList(new Address(param0),
            new Address(param1)),
            Arrays.<TypeReference<?>>asList(new TypeReference<Uint256>() {}));
    return executeRemoteCallSingleValueReturn(function, BigInteger.class);
}
 
Example #21
Source File: PublicResolver.java    From web3j with Apache License 2.0 5 votes vote down vote up
public RemoteCall<Tuple2<byte[], byte[]>> pubkey(byte[] node) {
    final Function function = new Function(FUNC_PUBKEY, 
            Arrays.<Type>asList(new org.web3j.abi.datatypes.generated.Bytes32(node)), 
            Arrays.<TypeReference<?>>asList(new TypeReference<Bytes32>() {}, new TypeReference<Bytes32>() {}));
    return new RemoteCall<Tuple2<byte[], byte[]>>(
            new Callable<Tuple2<byte[], byte[]>>() {
                @Override
                public Tuple2<byte[], byte[]> call() throws Exception {
                    List<Type> results = executeCallMultipleValueReturn(function);
                    return new Tuple2<byte[], byte[]>(
                            (byte[]) results.get(0).getValue(), 
                            (byte[]) results.get(1).getValue());
                }
            });
}
 
Example #22
Source File: SimpleStorage.java    From ethsigner with Apache License 2.0 5 votes vote down vote up
public RemoteFunctionCall<TransactionReceipt> set(BigInteger value) {
  final Function function =
      new Function(
          FUNC_SET,
          Arrays.<Type>asList(new org.web3j.abi.datatypes.generated.Uint256(value)),
          Collections.<TypeReference<?>>emptyList());
  return executeRemoteCallTransaction(function);
}
 
Example #23
Source File: PublicResolver.java    From web3j with Apache License 2.0 5 votes vote down vote up
public RemoteCall<TransactionReceipt> setAddr(byte[] node, String addr) {
    final Function function = new Function(
            FUNC_SETADDR, 
            Arrays.<Type>asList(new org.web3j.abi.datatypes.generated.Bytes32(node), 
            new org.web3j.abi.datatypes.Address(addr)), 
            Collections.<TypeReference<?>>emptyList());
    return executeRemoteCallTransaction(function);
}
 
Example #24
Source File: Contract.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
protected <T extends Type> T executeCallSingleValueReturn(
        Function function) throws IOException {
    List<Type> values = executeCall(function);
    if (!values.isEmpty()) {
        return (T) values.get(0);
    } else {
        return null;
    }
}
 
Example #25
Source File: FunctionReturnDecoderTest.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testFunctionEmptyStringResultDecode() {
    Function function = new Function("test",
            Collections.emptyList(),
            Collections.singletonList(new TypeReference<Utf8String>() {
            }));

    List<Type> utf8Strings = FunctionReturnDecoder.decode(
            "0x0000000000000000000000000000000000000000000000000000000000000020"
                    + "0000000000000000000000000000000000000000000000000000000000000000",
            function.getOutputParameters());

    assertThat(utf8Strings.get(0).getValue(), is(""));
}
 
Example #26
Source File: HumanStandardToken.java    From web3j-quorum with Apache License 2.0 5 votes vote down vote up
public RemoteCall<TransactionReceipt> transferFrom(String _from, String _to, BigInteger _value) {
    final Function function = new Function(
            FUNC_TRANSFERFROM,
            Arrays.<Type>asList(new org.web3j.abi.datatypes.Address(_from),
                    new org.web3j.abi.datatypes.Address(_to),
                    new org.web3j.abi.datatypes.generated.Uint256(_value)),
            Collections.<TypeReference<?>>emptyList());
    return executeRemoteCallTransaction(function);
}
 
Example #27
Source File: HumanStandardToken.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
public RemoteCall<TransactionReceipt> approveAndCall(String _spender, BigInteger _value, byte[] _extraData) {
    final Function function = new Function(
            "approveAndCall", 
            Arrays.<Type>asList(new org.web3j.abi.datatypes.Address(_spender), 
            new org.web3j.abi.datatypes.generated.Uint256(_value), 
            new org.web3j.abi.datatypes.DynamicBytes(_extraData)), 
            Collections.<TypeReference<?>>emptyList());
    return executeRemoteCallTransaction(function);
}
 
Example #28
Source File: SolidityFunctionWrapper.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
private static void buildVariableLengthReturnFunctionConstructor(
        MethodSpec.Builder methodBuilder, String functionName, String inputParameters,
        List<TypeName> outputParameterTypes) throws ClassNotFoundException {

    List<Object> objects = new ArrayList<>();
    objects.add(Function.class);
    objects.add(Function.class);
    objects.add(functionName);

    objects.add(Arrays.class);
    objects.add(Type.class);
    objects.add(inputParameters);

    objects.add(Arrays.class);
    objects.add(TypeReference.class);
    for (TypeName outputParameterType : outputParameterTypes) {
        objects.add(TypeReference.class);
        objects.add(outputParameterType);
    }

    String asListParams = Collection.join(
            outputParameterTypes,
            ", ",
            typeName -> "new $T<$T>() {}");

    methodBuilder.addStatement("final $T function = new $T($S, \n$T.<$T>asList($L), \n$T"
            + ".<$T<?>>asList("
            + asListParams + "))", objects.toArray());
}
 
Example #29
Source File: TokenERC20.java    From Android-Wallet-Token-ERC20 with Apache License 2.0 5 votes vote down vote up
public RemoteCall<TransactionReceipt> transfer(String _to, BigInteger _value) {
    Function function = new Function(
            "transfer",
            Arrays.<Type>asList(new Address(_to),
            new Uint256(_value)),
            Collections.<TypeReference<?>>emptyList());
    return executeRemoteCallTransaction(function);
}
 
Example #30
Source File: Greeter.java    From web3j with Apache License 2.0 5 votes vote down vote up
public Flowable<ModifiedEventResponse> modifiedEventFlowable(EthFilter filter) {
    return web3j.ethLogFlowable(filter).map(new io.reactivex.functions.Function<Log, ModifiedEventResponse>() {
        @Override
        public ModifiedEventResponse apply(Log log) {
            Contract.EventValuesWithLog eventValues = extractEventParametersWithLog(MODIFIED_EVENT, log);
            ModifiedEventResponse typedResponse = new ModifiedEventResponse();
            typedResponse.log = log;
            typedResponse.oldGreetingIdx = (byte[]) eventValues.getIndexedValues().get(0).getValue();
            typedResponse.newGreetingIdx = (byte[]) eventValues.getIndexedValues().get(1).getValue();
            typedResponse.oldGreeting = (String) eventValues.getNonIndexedValues().get(0).getValue();
            typedResponse.newGreeting = (String) eventValues.getNonIndexedValues().get(1).getValue();
            return typedResponse;
        }
    });
}