org.web3j.protocol.Web3j Java Examples

The following examples show how to use org.web3j.protocol.Web3j. 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: Web3jUtils.java    From web3j_demo with Apache License 2.0 7 votes vote down vote up
/**
 * Transfers the specified amount of Wei from the coinbase to the specified account.
 * The method waits for the transfer to complete using method {@link waitForReceipt}.  
 */
public static TransactionReceipt transferFromCoinbaseAndWait(Web3j web3j, String to, BigInteger amountWei) 
		throws Exception 
{
	String coinbase = getCoinbase(web3j).getResult();
	BigInteger nonce = getNonce(web3j, coinbase);
	// this is a contract method call -> gas limit higher than simple fund transfer
	BigInteger gasLimit = Web3jConstants.GAS_LIMIT_ETHER_TX.multiply(BigInteger.valueOf(2)); 
	Transaction transaction = Transaction.createEtherTransaction(
			coinbase, 
			nonce, 
			Web3jConstants.GAS_PRICE, 
			gasLimit, 
			to, 
			amountWei);

	EthSendTransaction ethSendTransaction = web3j
			.ethSendTransaction(transaction)
			.sendAsync()
			.get();

	String txHash = ethSendTransaction.getTransactionHash();
	
	return waitForReceipt(web3j, txHash);
}
 
Example #2
Source File: MethodSpecGeneratorTest.java    From web3j with Apache License 2.0 7 votes vote down vote up
@Test
public void testGenerate() {
    List<ParameterSpec> parameterSpec =
            Collections.singletonList(
                    ParameterSpec.builder(Web3j.class, "web3j", Modifier.FINAL).build());
    String javaPoetStringFormat1 = "$T $L = $S";
    Object[] replacementValues1 = new Object[] {String.class, "hello ", "Hello how are you"};
    String javaPoetStringFormat2 = "$T $L = $T.build()";
    Object[] replacementValues2 = new Object[] {Web3j.class, "web3j", Web3j.class};
    Map<String, Object[]> statementBody = new LinkedHashMap<>();
    statementBody.put(javaPoetStringFormat1, replacementValues1);
    statementBody.put(javaPoetStringFormat2, replacementValues2);
    MethodSpecGenerator methodSpecGenerator =
            new MethodSpecGenerator(
                    "unitTest", Test.class, Modifier.PUBLIC, parameterSpec, statementBody);
    MethodSpec generatedMethodSpec = methodSpecGenerator.generate();
    assertEquals(
            "@org.junit.jupiter.api.Test\n"
                    + "public void unitTest(final org.web3j.protocol.Web3j web3j) throws java.lang.Exception {\n"
                    + "  java.lang.String hello  = \"Hello how are you\";\n"
                    + "  org.web3j.protocol.Web3j web3j = org.web3j.protocol.Web3j.build();\n"
                    + "}\n",
            generatedMethodSpec.toString());
}
 
Example #3
Source File: TransactionRepository.java    From trust-wallet-android-source with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Single<String> createTransaction(Wallet from, String toAddress, BigInteger subunitAmount, BigInteger gasPrice, BigInteger gasLimit, byte[] data, String password) {
	final Web3j web3j = Web3jFactory.build(new HttpService(networkRepository.getDefaultNetwork().rpcServerUrl));

	return Single.fromCallable(() -> {
		EthGetTransactionCount ethGetTransactionCount = web3j
				.ethGetTransactionCount(from.address, DefaultBlockParameterName.LATEST)
				.send();
		return ethGetTransactionCount.getTransactionCount();
	})
	.flatMap(nonce -> accountKeystoreService.signTransaction(from, password, toAddress, subunitAmount, gasPrice, gasLimit, nonce.longValue(), data, networkRepository.getDefaultNetwork().chainId))
	.flatMap(signedMessage -> Single.fromCallable( () -> {
		EthSendTransaction raw = web3j
				.ethSendRawTransaction(Numeric.toHexString(signedMessage))
				.send();
		if (raw.hasError()) {
			throw new ServiceException(raw.getError().getMessage());
		}
		return raw.getTransactionHash();
	})).subscribeOn(Schedulers.io());
}
 
Example #4
Source File: EthereumUtils.java    From jbpm-work-items with Apache License 2.0 6 votes vote down vote up
public static Optional<TransactionReceipt> getTransactionReceipt(
        String transactionHash,
        int sleepDuration,
        int attempts,
        Web3j web3j) throws Exception {

    Optional<TransactionReceipt> receiptOptional =
            sendTransactionReceiptRequest(transactionHash,
                                          web3j);
    for (int i = 0; i < attempts; i++) {
        if (!receiptOptional.isPresent()) {
            Thread.sleep(sleepDuration);
            receiptOptional = sendTransactionReceiptRequest(transactionHash,
                                                            web3j);
        } else {
            break;
        }
    }

    return receiptOptional;
}
 
Example #5
Source File: EthereumRecordCursor.java    From presto-ethereum with Apache License 2.0 6 votes vote down vote up
public EthereumRecordCursor(List<EthereumColumnHandle> columnHandles, EthBlock block, EthereumTable table, Web3j web3j) {
    this.columnHandles = columnHandles;
    this.table = table;
    this.web3j = web3j;
    this.suppliers = Collections.emptyList();

    fieldToColumnIndex = new int[columnHandles.size()];
    for (int i = 0; i < columnHandles.size(); i++) {
        EthereumColumnHandle columnHandle = columnHandles.get(i);
        fieldToColumnIndex[i] = columnHandle.getOrdinalPosition();
    }

    // TODO: handle failure upstream
    this.block = requireNonNull(block, "block is null");
    this.blockIter = ImmutableList.of(block).iterator();
    this.txIter = block.getBlock().getTransactions().iterator();
    this.logIter = new EthereumLogLazyIterator(block, web3j);
}
 
Example #6
Source File: OnChainPrivacyGroupManagementProxy.java    From besu with Apache License 2.0 6 votes vote down vote up
public static RemoteCall<OnChainPrivacyGroupManagementProxy> deploy(
    Web3j web3j,
    Credentials credentials,
    ContractGasProvider contractGasProvider,
    String _implementation) {
  String encodedConstructor =
      FunctionEncoder.encodeConstructor(
          Arrays.<Type>asList(new org.web3j.abi.datatypes.Address(160, _implementation)));
  return deployRemoteCall(
      OnChainPrivacyGroupManagementProxy.class,
      web3j,
      credentials,
      contractGasProvider,
      BINARY,
      encodedConstructor);
}
 
Example #7
Source File: Contract.java    From web3j with Apache License 2.0 6 votes vote down vote up
@Deprecated
protected static <T extends Contract> T deploy(
        Class<T> type,
        Web3j web3j,
        TransactionManager transactionManager,
        BigInteger gasPrice,
        BigInteger gasLimit,
        String binary,
        String encodedConstructor,
        BigInteger value)
        throws RuntimeException, TransactionException {

    return deploy(
            type,
            web3j,
            transactionManager,
            new StaticGasProvider(gasPrice, gasLimit),
            binary,
            encodedConstructor,
            value);
}
 
Example #8
Source File: TransactionHandler.java    From alpha-wallet-android with MIT License 6 votes vote down vote up
public TransactionHandler(int networkId)
{
    String nodeURL = EthereumNetworkBase.getNetworkByChain(networkId).rpcServerUrl;
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.connectTimeout(20, TimeUnit.SECONDS);
    builder.readTimeout(20, TimeUnit.SECONDS);
    HttpService service = new HttpService(nodeURL, builder.build(), false);
    mWeb3 = Web3j.build(service);
    try
    {
        Web3ClientVersion web3ClientVersion = mWeb3.web3ClientVersion().sendAsync().get();
        System.out.println(web3ClientVersion.getWeb3ClientVersion());
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}
 
Example #9
Source File: Web3jUtils.java    From web3j_demo with Apache License 2.0 6 votes vote down vote up
/**
 * Waits for the receipt for the transaction specified by the provided tx hash.
 * Makes 40 attempts (waiting 1 sec. inbetween attempts) to get the receipt object.
 * In the happy case the tx receipt object is returned.
 * Otherwise, a runtime exception is thrown. 
 */
public static TransactionReceipt waitForReceipt(Web3j web3j, String transactionHash) 
		throws Exception 
{

	int attempts = Web3jConstants.CONFIRMATION_ATTEMPTS;
	int sleep_millis = Web3jConstants.SLEEP_DURATION;
	
	Optional<TransactionReceipt> receipt = getReceipt(web3j, transactionHash);

	while(attempts-- > 0 && !receipt.isPresent()) {
		Thread.sleep(sleep_millis);
		receipt = getReceipt(web3j, transactionHash);
	}

	if (attempts <= 0) {
		throw new RuntimeException("No Tx receipt received");
	}

	return receipt.get();
}
 
Example #10
Source File: Contract.java    From web3j with Apache License 2.0 6 votes vote down vote up
@Deprecated
protected Contract(
        String contractBinary,
        String contractAddress,
        Web3j web3j,
        Credentials credentials,
        BigInteger gasPrice,
        BigInteger gasLimit) {
    this(
            contractBinary,
            contractAddress,
            web3j,
            new RawTransactionManager(web3j, credentials),
            gasPrice,
            gasLimit);
}
 
Example #11
Source File: CreateTransactionInteract.java    From Upchain-wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
public Single<String> createTransaction(ETHWallet from, BigInteger gasPrice, BigInteger gasLimit, String data, String password) {

        final Web3j web3j = Web3j.build(new HttpService(networkRepository.getDefaultNetwork().rpcServerUrl));

        return networkRepository.getLastTransactionNonce(web3j, from.address)
                .flatMap(nonce -> getRawTransaction(nonce, gasPrice, gasLimit, BigInteger.ZERO, data))
                .flatMap(rawTx -> signEncodeRawTransaction(rawTx, password, from, networkRepository.getDefaultNetwork().chainId))
                .flatMap(signedMessage -> Single.fromCallable( () -> {
                    EthSendTransaction raw = web3j
                            .ethSendRawTransaction(Numeric.toHexString(signedMessage))
                            .send();
                    if (raw.hasError()) {
                        throw new Exception(raw.getError().getMessage());
                    }
                    return raw.getTransactionHash();
                })).subscribeOn(Schedulers.io());

    }
 
Example #12
Source File: WalletSendFunds.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
private void run(String walletFileLocation, String destinationAddress) {
    File walletFile = new File(walletFileLocation);
    Credentials credentials = getCredentials(walletFile);
    console.printf("Wallet for address " + credentials.getAddress() + " loaded\n");

    if (!WalletUtils.isValidAddress(destinationAddress)
            && !EnsResolver.isValidEnsName(destinationAddress)) {
        exitError("Invalid destination address specified");
    }

    Web3j web3j = getEthereumClient();

    BigDecimal amountToTransfer = getAmountToTransfer();
    Convert.Unit transferUnit = getTransferUnit();
    BigDecimal amountInWei = Convert.toWei(amountToTransfer, transferUnit);

    confirmTransfer(amountToTransfer, transferUnit, amountInWei, destinationAddress);

    TransactionReceipt transactionReceipt = performTransfer(
            web3j, destinationAddress, credentials, amountInWei);

    console.printf("Funds have been successfully transferred from %s to %s%n"
                    + "Transaction hash: %s%nMined block number: %s%n",
            credentials.getAddress(),
            destinationAddress,
            transactionReceipt.getTransactionHash(),
            transactionReceipt.getBlockNumber());
}
 
Example #13
Source File: DepositContract.java    From teku with Apache License 2.0 5 votes vote down vote up
@Deprecated
protected DepositContract(
    String contractAddress,
    Web3j web3j,
    TransactionManager transactionManager,
    BigInteger gasPrice,
    BigInteger gasLimit) {
  super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit);
}
 
Example #14
Source File: SimpleStorage.java    From besu with Apache License 2.0 5 votes vote down vote up
@Deprecated
public static SimpleStorage load(
    final String contractAddress,
    final Web3j web3j,
    final Credentials credentials,
    final BigInteger gasPrice,
    final BigInteger gasLimit) {
  return new SimpleStorage(contractAddress, web3j, credentials, gasPrice, gasLimit);
}
 
Example #15
Source File: EthereumUtils.java    From jbpm-work-items with Apache License 2.0 5 votes vote down vote up
public static BigInteger getNextNonce(String address,
                                      Web3j web3j) throws Exception {
    EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(
            address,
            DefaultBlockParameterName.LATEST).sendAsync().get();
    return ethGetTransactionCount.getTransactionCount();
}
 
Example #16
Source File: BDSMicroRaidenjSingleton.java    From asf-sdk with GNU General Public License v3.0 5 votes vote down vote up
public static MicroRaidenBDS create(boolean debug) {
  Web3j web3j =
      Web3jFactory.build(new HttpService("https://ropsten.infura.io/1YsvKO0VH5aBopMYJzcy"));
  AsfWeb3jImpl asfWeb3j = new AsfWeb3jImpl(web3j);

  TransactionSender transactionSender =
      new DefaultTransactionSender(web3j, () -> BigInteger.valueOf(50000000000L),
          new DefaultNonceObtainer(asfWeb3j), new DefaultGasLimitEstimator(web3j));

  return new DefaultMicroRaidenBDS(
      new DefaultMicroRaidenClient(channelManagerAddr, BigInteger.valueOf(13),
          new DefaultChannelBlockObtainer(web3j, 3, 1500),
          new MicroRaidenContract(channelManagerAddr, tokenAddr, transactionSender)),
      BDSMicroRaidenApi.create(debug));
}
 
Example #17
Source File: TokenRepository.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
private Web3j getService(int chainId)
{
    if (!web3jNodeServers.containsKey(chainId))
    {
        buildWeb3jClient(ethereumNetworkRepository.getNetworkByChain(chainId));
    }
    return web3jNodeServers.get(chainId);
}
 
Example #18
Source File: MethodFilterTest.java    From web3j with Apache License 2.0 5 votes vote down vote up
@Test
public void testThatTheCorrectDeployMethodWasExtracted() {
    List<Method> filteredMethods = MethodFilter.extractValidMethods(greeterContractClass);
    List<Method> deployMethod =
            filteredMethods.stream()
                    .filter(m -> m.getName().equals("deploy"))
                    .collect(Collectors.toList());
    List<Class<?>> deployMethodParameterTypes =
            Arrays.asList(deployMethod.get(0).getParameterTypes());
    assertTrue(
            deployMethodParameterTypes.containsAll(
                    Arrays.asList(
                            Web3j.class, TransactionManager.class, ContractGasProvider.class)));
}
 
Example #19
Source File: CrossContractReader.java    From besu with Apache License 2.0 5 votes vote down vote up
@Deprecated
protected CrossContractReader(
    final String contractAddress,
    final Web3j web3j,
    final Credentials credentials,
    final BigInteger gasPrice,
    final BigInteger gasLimit) {
  super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit);
}
 
Example #20
Source File: FastRawTransactionManager.java    From web3j with Apache License 2.0 5 votes vote down vote up
public FastRawTransactionManager(
        Web3j web3j,
        Credentials credentials,
        long chainId,
        TransactionReceiptProcessor transactionReceiptProcessor) {
    super(web3j, credentials, chainId, transactionReceiptProcessor);
}
 
Example #21
Source File: NodeBeanRegistrationStrategy.java    From eventeum with Apache License 2.0 5 votes vote down vote up
public void register(Node node, BeanDefinitionRegistry registry) {
    registerContractEventDetailsFactoryBean(node, registry);

    final Web3jService web3jService = buildWeb3jService(node);
    final Web3j web3j = buildWeb3j(node, web3jService);
    final String blockchainServiceBeanName = registerBlockchainServiceBean(node, web3j, registry);
    registerNodeServicesBean(node, web3j, blockchainServiceBeanName, registry);
    final String nodeFailureListenerBeanName =
            registerNodeFailureListener(node, blockchainServiceBeanName, web3jService, registry);
    registerNodeHealthCheckBean(node, blockchainServiceBeanName, web3jService, nodeFailureListenerBeanName, registry);


}
 
Example #22
Source File: CrossContractReader.java    From besu with Apache License 2.0 5 votes vote down vote up
public static CrossContractReader load(
    final String contractAddress,
    final Web3j web3j,
    final TransactionManager transactionManager,
    final ContractGasProvider contractGasProvider) {
  return new CrossContractReader(contractAddress, web3j, transactionManager, contractGasProvider);
}
 
Example #23
Source File: SimpleStorage.java    From ethsigner with Apache License 2.0 5 votes vote down vote up
@Deprecated
protected SimpleStorage(
    String contractAddress,
    Web3j web3j,
    Credentials credentials,
    BigInteger gasPrice,
    BigInteger gasLimit) {
  super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit);
}
 
Example #24
Source File: Web3jUtils.java    From web3j_demo with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the list of addresses owned by this client.
 */
public static EthAccounts getAccounts(Web3j web3j) throws InterruptedException, ExecutionException {
	return web3j
			.ethAccounts()
			.sendAsync()
			.get();
}
 
Example #25
Source File: OnChainPrivacyGroupManagementInterface.java    From besu with Apache License 2.0 5 votes vote down vote up
@Deprecated
public static OnChainPrivacyGroupManagementInterface load(
    String contractAddress,
    Web3j web3j,
    TransactionManager transactionManager,
    BigInteger gasPrice,
    BigInteger gasLimit) {
  return new OnChainPrivacyGroupManagementInterface(
      contractAddress, web3j, transactionManager, gasPrice, gasLimit);
}
 
Example #26
Source File: QueuingTransactionReceiptProcessor.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
public QueuingTransactionReceiptProcessor(
        Web3j web3j, Callback callback,
        int pollingAttemptsPerTxHash, long pollingFrequency) {
    super(web3j);
    this.scheduledExecutorService = Async.defaultExecutorService();
    this.callback = callback;
    this.pendingTransactions = new LinkedBlockingQueue<>();
    this.pollingAttemptsPerTxHash = pollingAttemptsPerTxHash;

    scheduledExecutorService.scheduleAtFixedRate(
            this::sendTransactionReceiptRequests,
            pollingFrequency, pollingFrequency, TimeUnit.MILLISECONDS);
}
 
Example #27
Source File: Contract.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
protected Contract(String contractBinary, String contractAddress,
                   Web3j web3j, TransactionManager transactionManager,
                   GasProvider gasProvider) {
    super(web3j, transactionManager);

    this.contractAddress = contractAddress;

    this.contractBinary = contractBinary;
    this.gasProvider = gasProvider;
}
 
Example #28
Source File: PubSubBlockchainSubscriptionStrategyTest.java    From eventeum with Apache License 2.0 5 votes vote down vote up
@Before
public void init() throws IOException {
    this.mockWeb3j = mock(Web3j.class);

    mockNewHeadsNotification = mock(NewHeadsNotification.class);
    mockEventStoreService = mock(EventStoreService.class);
    when(mockNewHeadsNotification.getParams()).thenReturn(new NewHeadNotificationParameter());

    mockNewHead = mock(NewHead.class);
    when(mockNewHead.getHash()).thenReturn(BLOCK_HASH);

    blockPublishProcessor = PublishProcessor.create();
    when(mockWeb3j.newHeadsNotifications()).thenReturn(blockPublishProcessor);

    mockEthBlock = mock(EthBlock.class);
    final EthBlock.Block mockBlock = mock(EthBlock.Block.class);

    when(mockBlock.getNumber()).thenReturn(BLOCK_NUMBER);
    when(mockBlock.getHash()).thenReturn(BLOCK_HASH);
    when(mockBlock.getTimestamp()).thenReturn(Numeric.toBigInt(BLOCK_TIMESTAMP));
    when(mockEthBlock.getBlock()).thenReturn(mockBlock);

    final Request<?, EthBlock> mockRequest = mock(Request.class);
    doReturn(mockRequest).when(mockWeb3j).ethGetBlockByHash(BLOCK_HASH, true);

    when(mockRequest.send()).thenReturn(mockEthBlock);

    underTest = new PubSubBlockSubscriptionStrategy(mockWeb3j, NODE_NAME,
            mockEventStoreService, new DummyAsyncTaskService());
}
 
Example #29
Source File: OnChainPrivacyGroupManagementInterface.java    From besu with Apache License 2.0 5 votes vote down vote up
public static RemoteCall<OnChainPrivacyGroupManagementInterface> deploy(
    Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) {
  return deployRemoteCall(
      OnChainPrivacyGroupManagementInterface.class,
      web3j,
      transactionManager,
      contractGasProvider,
      BINARY,
      "");
}
 
Example #30
Source File: RawTransactionManager.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
public RawTransactionManager(Web3j web3j, Credentials credentials, byte chainId) {
    super(web3j, credentials.getAddress());

    this.web3j = web3j;
    this.credentials = credentials;

    this.chainId = chainId;
}