org.web3j.abi.datatypes.Address Java Examples

The following examples show how to use org.web3j.abi.datatypes.Address. 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: SendingTokensActivity.java    From guarda-android-wallets with GNU General Public License v3.0 7 votes vote down vote up
private String getContractTransfer() {
    int tokenDecimals = tokensManager.getTokenByCode(tokenCode).getDecimal();
    BigInteger tokenValue = Converter.toDecimals(new BigDecimal(amountToSend), tokenDecimals).toBigInteger();
    List<Type> inputParams = new ArrayList<>();

    Type address = new Address(walletNumber);
    inputParams.add(address);

    Type value = new Uint(tokenValue);
    inputParams.add(value);

    Function function = new Function(
            "transfer",
            inputParams,
            Collections.<TypeReference<?>>emptyList());

    return FunctionEncoder.encode(function);
}
 
Example #2
Source File: SendingTokensActivity.java    From guarda-android-wallets with GNU General Public License v3.0 6 votes vote down vote up
private String getContractTransfer() {
    int tokenDecimals = tokensManager.getTokenByCode(tokenCode).getDecimal();
    BigInteger tokenValue = Converter.toDecimals(new BigDecimal(amountToSend), tokenDecimals).toBigInteger();
    List<Type> inputParams = new ArrayList<>();

    Type address = new Address(walletNumber);
    inputParams.add(address);

    Type value = new Uint(tokenValue);
    inputParams.add(value);

    Function function = new Function(
            "transfer",
            inputParams,
            Collections.<TypeReference<?>>emptyList());

    return FunctionEncoder.encode(function);
}
 
Example #3
Source File: TokenERC20.java    From Android-Wallet-Token-ERC20 with Apache License 2.0 6 votes vote down vote up
public Observable<BurnEventResponse> burnEventObservable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) {
    final Event event = new Event("Burn", 
            Arrays.<TypeReference<?>>asList(new TypeReference<Address>() {}),
            Arrays.<TypeReference<?>>asList(new TypeReference<Uint256>() {}));
    EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress());
    filter.addSingleTopic(EventEncoder.encode(event));
    return web3j.ethLogObservable(filter).map(new Func1<Log, BurnEventResponse>() {
        @Override
        public BurnEventResponse call(Log log) {
            EventValues eventValues = extractEventParameters(event, log);
            BurnEventResponse typedResponse = new BurnEventResponse();
            typedResponse.from = (String) eventValues.getIndexedValues().get(0).getValue();
            typedResponse.value = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue();
            return typedResponse;
        }
    });
}
 
Example #4
Source File: PublicResolver.java    From etherscan-explorer with GNU General Public License v3.0 6 votes vote down vote up
public Observable<AddrChangedEventResponse> addrChangedEventObservable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) {
    final Event event = new Event("AddrChanged", 
            Arrays.<TypeReference<?>>asList(new TypeReference<Bytes32>() {}),
            Arrays.<TypeReference<?>>asList(new TypeReference<Address>() {}));
    EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress());
    filter.addSingleTopic(EventEncoder.encode(event));
    return web3j.ethLogObservable(filter).map(new Func1<Log, AddrChangedEventResponse>() {
        @Override
        public AddrChangedEventResponse call(Log log) {
            EventValues eventValues = extractEventParameters(event, log);
            AddrChangedEventResponse typedResponse = new AddrChangedEventResponse();
            typedResponse.node = (byte[]) eventValues.getIndexedValues().get(0).getValue();
            typedResponse.a = (String) eventValues.getNonIndexedValues().get(0).getValue();
            return typedResponse;
        }
    });
}
 
Example #5
Source File: PayWages.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
public RemoteCall<Tuple4<BigInteger, BigInteger, String, String>> getEmployee(String _account) {
	final Function function = new Function(FUNC_GETEMPLOYEE, Arrays.<Type>asList(new org.web3j.abi.datatypes.Address(_account)),
			Arrays.<TypeReference<?>>asList(new TypeReference<Uint256>() {
			}, new TypeReference<Uint8>() {
			}, new TypeReference<Utf8String>() {
			}, new TypeReference<Address>() {
			}));
	return new RemoteCall<Tuple4<BigInteger, BigInteger, String, String>>(new Callable<Tuple4<BigInteger, BigInteger, String, String>>() {
		@Override
		public Tuple4<BigInteger, BigInteger, String, String> call() throws Exception {
			List<Type> results = executeCallMultipleValueReturn(function);
			return new Tuple4<BigInteger, BigInteger, String, String>((BigInteger) results.get(0).getValue(),
					(BigInteger) results.get(1).getValue(), (String) results.get(2).getValue(), (String) results.get(3).getValue());
		}
	});
}
 
Example #6
Source File: Web3jExtension.java    From web3j-gradle-plugin with Apache License 2.0 6 votes vote down vote up
public Web3jExtension(final Project project) {
    generatedFilesBaseDir =
            project.getBuildDir().getAbsolutePath() + "/generated/source/" + NAME;

    // Use the project's group name in generated package
    final String projectGroup = project.getGroup().toString();
    if (!projectGroup.isEmpty()) {
        generatedPackageName = projectGroup + "." + NAME;
    } else {
        generatedPackageName = DEFAULT_GENERATED_PACKAGE;
    }

    useNativeJavaTypes = true;
    excludedContracts = new ArrayList<>();
    includedContracts = new ArrayList<>();
    addressBitLength = Address.DEFAULT_LENGTH / Byte.SIZE;
}
 
Example #7
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 #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: TransactionManager.java    From BitcoinWallet with MIT License 6 votes vote down vote up
public String signContractTransaction(String contractAddress,
                                      String to,
                                      BigInteger nonce,
                                      BigInteger gasPrice,
                                      BigInteger gasLimit,
                                      BigDecimal amount,
                                      BigDecimal decimal,
                                      WalletFile walletfile,
                                      String password) throws Exception {
    BigDecimal realValue = amount.multiply(decimal);
    Function function = new Function("transfer",
            Arrays.asList(new Address(to), new Uint256(realValue.toBigInteger())),
            Collections.emptyList());
    String data = FunctionEncoder.encode(function);
    RawTransaction rawTransaction = RawTransaction.createTransaction(
            nonce,
            gasPrice,
            gasLimit,
            contractAddress,
            data);
    return signData(rawTransaction, walletfile, password);
}
 
Example #10
Source File: AbiTypesMapperGenerator.java    From etherscan-explorer with GNU General Public License v3.0 6 votes vote down vote up
private MethodSpec.Builder addTypes(MethodSpec.Builder builder, String packageName) {
    builder = addStatement(builder, packageName,
            Address.TYPE_NAME, Address.class.getSimpleName());

    builder = addStatement(builder, packageName,
            Bool.TYPE_NAME, Bool.class.getSimpleName());

    builder = addStatement(builder, packageName,
            Utf8String.TYPE_NAME, Utf8String.class.getSimpleName());

    builder = addStatement(builder, packageName,
            DynamicBytes.TYPE_NAME, DynamicBytes.class.getSimpleName());

    // TODO: Fixed array & dynamic array support
    return builder;
}
 
Example #11
Source File: OnChainPrivacyGroupManagementProxy.java    From besu with Apache License 2.0 6 votes vote down vote up
public static RemoteCall<OnChainPrivacyGroupManagementProxy> deploy(
    Web3j web3j,
    TransactionManager transactionManager,
    ContractGasProvider contractGasProvider,
    String _implementation) {
  String encodedConstructor =
      FunctionEncoder.encodeConstructor(
          Arrays.<Type>asList(new org.web3j.abi.datatypes.Address(160, _implementation)));
  return deployRemoteCall(
      OnChainPrivacyGroupManagementProxy.class,
      web3j,
      transactionManager,
      contractGasProvider,
      BINARY,
      encodedConstructor);
}
 
Example #12
Source File: BlindAuction.java    From web3j with Apache License 2.0 6 votes vote down vote up
public RemoteCall<Tuple2<byte[], BigInteger>> bids(String param0, BigInteger param1) {
    final Function function = new Function(FUNC_BIDS,
            Arrays.<Type>asList(new org.web3j.abi.datatypes.Address(param0),
            new org.web3j.abi.datatypes.generated.Uint256(param1)), 
            Arrays.<TypeReference<?>>asList(new TypeReference<Bytes32>() {}, new TypeReference<Uint256>() {}));
    return new RemoteCall<Tuple2<byte[], BigInteger>>(
            new Callable<Tuple2<byte[], BigInteger>>() {
                @Override
                public Tuple2<byte[], BigInteger> call() throws Exception {
                    List<Type> results = executeCallMultipleValueReturn(function);
                    return new Tuple2<byte[], BigInteger>(
                            (byte[]) results.get(0).getValue(), 
                            (BigInteger) results.get(1).getValue());
                }
            });
}
 
Example #13
Source File: TypeEncoderTest.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testAddress() {
    Address address = new Address("0xbe5422d15f39373eb0a97ff8c10fbd0e40e29338");
    assertThat(address.getTypeAsString(), is("address"));
    assertThat(TypeEncoder.encodeAddress(address),
            is("000000000000000000000000be5422d15f39373eb0a97ff8c10fbd0e40e29338"));
}
 
Example #14
Source File: SolidityFunctionWrapperTest.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testGetEventNativeTypeParameterized() {
    assertThat(getEventNativeType(
            ParameterizedTypeName.get(
                    ClassName.get(DynamicArray.class), TypeName.get(Address.class))),
            equalTo(TypeName.get(byte[].class)));
}
 
Example #15
Source File: ENS.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
public List<NewOwnerEventResponse> getNewOwnerEvents(TransactionReceipt transactionReceipt) {
    final Event event = new Event("NewOwner", 
            Arrays.<TypeReference<?>>asList(new TypeReference<Bytes32>() {}, new TypeReference<Bytes32>() {}),
            Arrays.<TypeReference<?>>asList(new TypeReference<Address>() {}));
    List<EventValues> valueList = extractEventParameters(event, transactionReceipt);
    ArrayList<NewOwnerEventResponse> responses = new ArrayList<NewOwnerEventResponse>(valueList.size());
    for (EventValues eventValues : valueList) {
        NewOwnerEventResponse typedResponse = new NewOwnerEventResponse();
        typedResponse.node = (byte[]) eventValues.getIndexedValues().get(0).getValue();
        typedResponse.label = (byte[]) eventValues.getIndexedValues().get(1).getValue();
        typedResponse.owner = (String) eventValues.getNonIndexedValues().get(0).getValue();
        responses.add(typedResponse);
    }
    return responses;
}
 
Example #16
Source File: TypeDecoder.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
static <T extends Type> T decode(String input, int offset, Class<T> type) {
    if (NumericType.class.isAssignableFrom(type)) {
        return (T) decodeNumeric(input.substring(offset), (Class<NumericType>) type);
    } else if (Address.class.isAssignableFrom(type)) {
        return (T) decodeAddress(input.substring(offset));
    } else if (Bool.class.isAssignableFrom(type)) {
        return (T) decodeBool(input, offset);
    } else if (Bytes.class.isAssignableFrom(type)) {
        return (T) decodeBytes(input, offset, (Class<Bytes>) type);
    } else if (DynamicBytes.class.isAssignableFrom(type)) {
        return (T) decodeDynamicBytes(input, offset);
    } else if (Utf8String.class.isAssignableFrom(type)) {
        return (T) decodeUtf8String(input, offset);
    } else if (Array.class.isAssignableFrom(type)) {
        throw new UnsupportedOperationException(
                "Array types must be wrapped in a TypeReference");
    } else {
        throw new UnsupportedOperationException(
                "Type cannot be encoded: " + type.getClass());
    }
}
 
Example #17
Source File: EnsResolver.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
private Function getAddr(byte[] nameHash)
{
    return new Function("addr",
                        Arrays.<Type>asList(new org.web3j.abi.datatypes.generated.Bytes32(nameHash)),
                        Arrays.<TypeReference<?>>asList(new TypeReference<Address>()
                        {
                        }));
}
 
Example #18
Source File: HumanStandardToken.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
public RemoteCall<TransactionReceipt> approve(String _spender, BigInteger _value) {
    final Function function = new Function(
            "approve", 
            Arrays.<Type>asList(new org.web3j.abi.datatypes.Address(_spender), 
            new org.web3j.abi.datatypes.generated.Uint256(_value)), 
            Collections.<TypeReference<?>>emptyList());
    return executeRemoteCallTransaction(function);
}
 
Example #19
Source File: BankAccountSmartContractTests.java    From devops-blockchain-jenkins with MIT License 5 votes vote down vote up
@Test
public void testAccountWithdrawalOverBalance() throws Exception {
	bankAccountContract.deposit(new Address(mainAccountAddress), new Uint256(100)).get();
	bankAccountContract.withdraw(new Address(mainAccountAddress), new Uint256(150)).get();
	
	Assert.assertEquals(100,
			bankAccountContract.balanceOf(new Address(mainAccountAddress)).get().getValue().intValue());
}
 
Example #20
Source File: PayWages.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
@Deprecated
public static RemoteCall<PayWages> deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit,
		BigInteger initialWeiValue, String _personnel, String _financer) {
	String encodedConstructor = FunctionEncoder.encodeConstructor(
			Arrays.<Type>asList(new org.web3j.abi.datatypes.Address(_personnel), new org.web3j.abi.datatypes.Address(_financer)));
	return deployRemoteCall(PayWages.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, encodedConstructor, initialWeiValue);
}
 
Example #21
Source File: ContractTest.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testTransactionFailed() throws Exception {
    thrown.expect(TransactionException.class);
    thrown.expectMessage(
            "Transaction has failed with status: 0x0. Gas used: 1. (not-enough gas?)");

    TransactionReceipt transactionReceipt = new TransactionReceipt();
    transactionReceipt.setTransactionHash(TRANSACTION_HASH);
    transactionReceipt.setStatus("0x0");
    transactionReceipt.setGasUsed("0x1");

    prepareTransaction(transactionReceipt);
    contract.performTransaction(
            new Address(BigInteger.TEN), new Uint256(BigInteger.ONE)).send();
}
 
Example #22
Source File: SolidityFunctionWrapperTest.java    From web3j with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetNativeTypeParameterized() {
    assertEquals(
            getNativeType(
                    ParameterizedTypeName.get(
                            ClassName.get(DynamicArray.class), TypeName.get(Address.class))),
            (ParameterizedTypeName.get(ClassName.get(List.class), TypeName.get(String.class))));
}
 
Example #23
Source File: SolidityFunctionWrapperTest.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testGetNativeTypeParameterized() {
    assertThat(getNativeType(
            ParameterizedTypeName.get(
                    ClassName.get(DynamicArray.class), TypeName.get(Address.class))),
            equalTo(ParameterizedTypeName.get(
                    ClassName.get(List.class), TypeName.get(String.class))));
}
 
Example #24
Source File: TokenRepository.java    From trust-wallet-android-source with GNU General Public License v3.0 5 votes vote down vote up
public static byte[] createTokenTransferData(String to, BigInteger tokenAmount) {
    List<Type> params = Arrays.<Type>asList(new Address(to), new Uint256(tokenAmount));

    List<TypeReference<?>> returnTypes = Arrays.<TypeReference<?>>asList(new TypeReference<Bool>() {
    });

    Function function = new Function("transfer", params, returnTypes);
    String encodedFunction = FunctionEncoder.encode(function);
    return Numeric.hexStringToByteArray(Numeric.cleanHexPrefix(encodedFunction));
}
 
Example #25
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 #26
Source File: TokenRepository.java    From ETHWallet with GNU General Public License v3.0 5 votes vote down vote up
private static org.web3j.abi.datatypes.Function balanceOf(String owner) {
    return new org.web3j.abi.datatypes.Function(
            "balanceOf",
            Collections.singletonList(new Address(owner)),
            Collections.singletonList(new TypeReference<Uint256>() {
            }));
}
 
Example #27
Source File: PayWages.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
public RemoteCall<TransactionReceipt> addEmployee(BigInteger _id, BigInteger _status, String _name, String _account) {
	final Function function = new Function(FUNC_ADDEMPLOYEE,
			Arrays.<Type>asList(new org.web3j.abi.datatypes.generated.Uint256(_id), new org.web3j.abi.datatypes.generated.Uint8(_status),
					new org.web3j.abi.datatypes.Utf8String(_name), new org.web3j.abi.datatypes.Address(_account)),
			Collections.<TypeReference<?>>emptyList());
	return executeRemoteCallTransaction(function);
}
 
Example #28
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 #29
Source File: TokenERC20.java    From Android-Wallet-Token-ERC20 with Apache License 2.0 5 votes vote down vote up
public RemoteCall<TransactionReceipt> transferFrom(String _from, String _to, BigInteger _value) {
    Function function = new Function(
            "transferFrom", 
            Arrays.<Type>asList(new Address(_from),
            new Address(_to),
            new Uint256(_value)),
            Collections.<TypeReference<?>>emptyList());
    return executeRemoteCallTransaction(function);
}
 
Example #30
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))));
}