Java Code Examples for org.web3j.protocol.Web3j#build()

The following examples show how to use org.web3j.protocol.Web3j#build() . 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: 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 2
Source File: BaseIntegrationTest.java    From eventeum with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {

    initRestTemplate();
    this.web3j = Web3j.build(new HttpService("http://localhost:8545"));
    this.admin = Admin.build(new HttpService("http://localhost:8545"));

    this.web3j.ethSendTransaction(Transaction.createEtherTransaction(
            this.web3j.ethAccounts().send().getAccounts().get(0),

            this.web3j.ethGetTransactionCount(
                this.web3j.ethAccounts().send().getAccounts().get(0),
                    DefaultBlockParameterName.fromString("latest")
            ).send().getTransactionCount(),

            BigInteger.valueOf(2000),
            BigInteger.valueOf(6721975),
            CREDS.getAddress(),
            new BigInteger("9460000000000000000"))
    ).send();

    dummyEventFilterId = UUID.randomUUID().toString();
    dummyEventNotOrderedFilterId = UUID.randomUUID().toString();

    clearMessages();

}
 
Example 3
Source File: RegisterAction.java    From teku with Apache License 2.0 5 votes vote down vote up
private DepositTransactionSender createTransactionSender() {
  httpClient = new OkHttpClient.Builder().connectionPool(new ConnectionPool()).build();
  executorService =
      Executors.newScheduledThreadPool(
          1, new ThreadFactoryBuilder().setDaemon(true).setNameFormat("web3j-%d").build());
  web3j = Web3j.build(new HttpService(eth1NodeUrl, httpClient), 1000, executorService);
  return new DepositTransactionSender(web3j, contractAddress, eth1Credentials);
}
 
Example 4
Source File: FetchGasSettingsInteract.java    From Upchain-wallet with GNU Affero General Public License v3.0 5 votes vote down vote up
public BigInteger getTransactionGasLimit(Transaction transaction) {

        final Web3j web3j = Web3j.build(new HttpService(networkRepository.getDefaultNetwork().rpcServerUrl));
        try {
            EthEstimateGas ethEstimateGas = web3j.ethEstimateGas(transaction).send();
            if (ethEstimateGas.hasError()){
                throw new RuntimeException(ethEstimateGas.getError().getMessage());
            }
            return ethEstimateGas.getAmountUsed();
        } catch (IOException e) {
            throw new RuntimeException("net error");
        }

    }
 
Example 5
Source File: TokenRepository.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
public static Web3j getWeb3jService(int chainId)
{
    OkHttpClient okClient = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .retryOnConnectionFailure(false)
            .build();
    AWHttpService publicNodeService = new AWHttpService(EthereumNetworkRepository.getNodeURLByNetworkId (chainId), EthereumNetworkRepository.getSecondaryNodeURL(chainId), okClient, false);
    EthereumNetworkRepository.addRequiredCredentials(chainId, publicNodeService);
    return Web3j.build(publicNodeService);
}
 
Example 6
Source File: WalletSendFunds.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
private Web3j getEthereumClient() {
    String clientAddress = console.readLine(
            "Please confirm address of running Ethereum client you wish to send "
            + "the transfer request to [" + HttpService.DEFAULT_URL + "]: ")
            .trim();

    Web3j web3j;
    if (clientAddress.equals("")) {
        web3j = Web3j.build(new HttpService());
    } else {
        web3j = Web3j.build(new HttpService(clientAddress));
    }

    try {
        Web3ClientVersion web3ClientVersion = web3j.web3ClientVersion().sendAsync().get();
        if (web3ClientVersion.hasError()) {
            exitError("Unable to process response from client: "
                    + web3ClientVersion.getError());
        } else {
            console.printf("Connected successfully to client: %s%n",
                    web3ClientVersion.getWeb3ClientVersion());
            return web3j;
        }
    } catch (InterruptedException | ExecutionException e) {
        exitError("Problem encountered verifying client: " + e.getMessage());
    }
    throw new RuntimeException("Application exit failure");
}
 
Example 7
Source File: GetBalanceWorkitemHandler.java    From jbpm-work-items with Apache License 2.0 5 votes vote down vote up
public void executeWorkItem(WorkItem workItem,
                            WorkItemManager workItemManager) {
    try {
        RequiredParameterValidator.validate(this.getClass(),
                                            workItem);

        String serviceURL = (String) workItem.getParameter("ServiceURL");

        Map<String, Object> results = new HashMap();

        if (web3j == null) {
            web3j = Web3j.build(new HttpService(serviceURL));
        }

        auth = new EthereumAuth(walletPassword,
                                walletPath,
                                classLoader);
        Credentials credentials = auth.getCredentials();

        results.put(RESULTS_VALUE,
                    EthereumUtils.getBalanceInEther(credentials,
                                                    web3j));

        workItemManager.completeWorkItem(workItem.getId(),
                                         results);
    } catch (Exception e) {
        logger.error("Error executing workitem: " + e.getMessage());
        handleException(e);
    }
}
 
Example 8
Source File: DeployContractWorkitemHandler.java    From jbpm-work-items with Apache License 2.0 4 votes vote down vote up
public void executeWorkItem(WorkItem workItem,
                            WorkItemManager workItemManager) {
    try {
        RequiredParameterValidator.validate(this.getClass(),
                                            workItem);

        String serviceURL = (String) workItem.getParameter("ServiceURL");
        String contractPath = (String) workItem.getParameter("ContractPath");
        String depositAmount = (String) workItem.getParameter("DepositAmount");
        String waitForReceiptStr = (String) workItem.getParameter("WaitForReceipt");

        Map<String, Object> results = new HashMap<String, Object>();

        if (web3j == null) {
            web3j = Web3j.build(new HttpService(serviceURL));
        }

        auth = new EthereumAuth(walletPassword,
                                walletPath,
                                classLoader);
        Credentials credentials = auth.getCredentials();

        int depositEtherAmountToSend = 0;
        if (depositAmount != null) {
            depositEtherAmountToSend = Integer.parseInt(depositAmount);
        }

        boolean waitForReceipt = false;
        if (waitForReceiptStr != null) {
            waitForReceipt = Boolean.parseBoolean(waitForReceiptStr);
        }

        String createdContractAddress = EthereumUtils.deployContract(credentials,
                                                                     web3j,
                                                                     EthereumUtils.convertStreamToStr(classLoader.getResourceAsStream(contractPath)),
                                                                     depositEtherAmountToSend,
                                                                     waitForReceipt,
                                                                     EthereumUtils.DEFAULT_SLEEP_DURATION,
                                                                     org.jbpm.process.workitem.ethereum.EthereumUtils.DEFAULT_ATTEMPTS);

        results.put(RESULTS,
                    createdContractAddress);

        workItemManager.completeWorkItem(workItem.getId(),
                                         results);
    } catch (Exception e) {
        logger.error("Error executing workitem: " + e.getMessage());
        handleException(e);
    }
}
 
Example 9
Source File: PowchainService.java    From teku with Apache License 2.0 4 votes vote down vote up
public PowchainService(final ServiceConfig config) {
  TekuConfiguration tekuConfig = config.getConfig();

  AsyncRunner asyncRunner = config.createAsyncRunner("powchain");

  final HttpService web3jService = new HttpService(tekuConfig.getEth1Endpoint());
  web3jService.addHeader("User-Agent", VersionProvider.VERSION);
  Web3j web3j = Web3j.build(web3jService);

  final Eth1Provider eth1Provider =
      new ThrottlingEth1Provider(
          new ErrorTrackingEth1Provider(
              new Web3jEth1Provider(web3j, asyncRunner), asyncRunner, config.getTimeProvider()),
          MAXIMUM_CONCURRENT_ETH1_REQUESTS);

  DepositContractAccessor depositContractAccessor =
      DepositContractAccessor.create(
          eth1Provider, web3j, config.getConfig().getEth1DepositContractAddress().toHexString());

  final Eth1EventsChannel eth1EventsChannel =
      config.getEventChannels().getPublisher(Eth1EventsChannel.class);
  final Eth1DepositStorageChannel eth1DepositStorageChannel =
      config.getEventChannels().getPublisher(Eth1DepositStorageChannel.class);
  final Eth1BlockFetcher eth1BlockFetcher =
      new Eth1BlockFetcher(
          eth1EventsChannel,
          eth1Provider,
          config.getTimeProvider(),
          calculateEth1DataCacheDurationPriorToCurrentTime());

  final DepositFetcher depositFetcher =
      new DepositFetcher(
          eth1Provider,
          eth1EventsChannel,
          depositContractAccessor.getContract(),
          eth1BlockFetcher,
          asyncRunner);

  headTracker = new Eth1HeadTracker(asyncRunner, eth1Provider);
  final DepositProcessingController depositProcessingController =
      new DepositProcessingController(
          eth1Provider,
          eth1EventsChannel,
          asyncRunner,
          depositFetcher,
          eth1BlockFetcher,
          headTracker);

  eth1DepositManager =
      new Eth1DepositManager(
          eth1Provider,
          asyncRunner,
          eth1EventsChannel,
          eth1DepositStorageChannel,
          depositProcessingController,
          new MinimumGenesisTimeBlockFinder(eth1Provider));
}
 
Example 10
Source File: CoreIT.java    From etherscan-explorer with GNU General Public License v3.0 4 votes vote down vote up
@Before
public void setUp() {
    //this.web3j = Web3j.build(new HttpService());
    this.web3j = Web3j.build(new UnixIpcService("/Users/bing/test/data/geth.ipc"));
}
 
Example 11
Source File: TransactExistingContractWorkitemHandler.java    From jbpm-work-items with Apache License 2.0 4 votes vote down vote up
public void executeWorkItem(WorkItem workItem,
                            WorkItemManager workItemManager) {
    try {
        RequiredParameterValidator.validate(this.getClass(),
                                            workItem);

        String serviceURL = (String) workItem.getParameter("ServiceURL");
        String contractAddress = (String) workItem.getParameter("ContractAddress");
        String waitForReceiptStr = (String) workItem.getParameter("WaitForReceipt");
        String methodName = (String) workItem.getParameter("MethodName");
        Type methodInputType = (Type) workItem.getParameter("MethodInputType");
        String depositAmount = (String) workItem.getParameter("DepositAmount");

        Map<String, Object> results = new HashMap<String, Object>();

        if (web3j == null) {
            web3j = Web3j.build(new HttpService(serviceURL));
        }

        auth = new EthereumAuth(walletPassword,
                                walletPath,
                                classLoader);
        Credentials credentials = auth.getCredentials();

        int depositEtherAmountToSend = 0;
        if (depositAmount != null) {
            depositEtherAmountToSend = Integer.parseInt(depositAmount);
        }

        boolean waitForReceipt = false;
        if (waitForReceiptStr != null) {
            waitForReceipt = Boolean.parseBoolean(waitForReceiptStr);
        }

        List<Type> methodInputTypeList = new ArrayList<>();
        if (methodInputType != null) {
            methodInputTypeList = Collections.singletonList(methodInputType);
        }

        TransactionReceipt transactionReceipt = EthereumUtils.transactExistingContract(
                credentials,
                web3j,
                depositEtherAmountToSend,
                EthereumUtils.DEFAULT_GAS_PRICE,
                EthereumUtils.DEFAULT_GAS_LIMIT,
                contractAddress,
                methodName,
                methodInputTypeList,
                null,
                waitForReceipt,
                EthereumUtils.DEFAULT_SLEEP_DURATION,
                EthereumUtils.DEFAULT_ATTEMPTS);

        results.put(RESULTS,
                    transactionReceipt);

        workItemManager.completeWorkItem(workItem.getId(),
                                         results);
    } catch (Exception e) {
        logger.error("Error executing workitem: " + e.getMessage());
        handleException(e);
    }
}
 
Example 12
Source File: RequestTest.java    From web3j with Apache License 2.0 4 votes vote down vote up
@Override
protected void initWeb3Client(HttpService httpService) {
    web3j = Web3j.build(httpService);
}
 
Example 13
Source File: ObserveContractEventWorkitemHandler.java    From jbpm-work-items with Apache License 2.0 4 votes vote down vote up
public void executeWorkItem(WorkItem workItem,
                            WorkItemManager workItemManager) {
    try {
        RequiredParameterValidator.validate(this.getClass(),
                                            workItem);

        String serviceURL = (String) workItem.getParameter("ServiceURL");
        String contractAddress = (String) workItem.getParameter("ContractAddress");
        String eventName = (String) workItem.getParameter("EventName");
        List<TypeReference<?>> eventIndexedParameter = (List<TypeReference<?>>) workItem.getParameter("EventIndexedParameter");
        List<TypeReference<?>> eventNonIndexedParameter = (List<TypeReference<?>>) workItem.getParameter("EventNonIndexedParameter");
        String eventReturnType = (String) workItem.getParameter("EventReturnType");
        String signalName = (String) workItem.getParameter("SignalName");
        String abortOnUpdate = (String) workItem.getParameter("AbortOnUpdate");

        boolean doAbortOnUpdate = Boolean.parseBoolean(abortOnUpdate);

        if (eventIndexedParameter == null) {
            eventIndexedParameter = new ArrayList<>();
        }

        if (eventNonIndexedParameter == null) {
            eventNonIndexedParameter = new ArrayList<>();
        }

        if (web3j == null) {
            web3j = Web3j.build(new HttpService(serviceURL));
        }

        KieSession localksession = ksession;
        RuntimeManager runtimeManager = null;
        RuntimeEngine engine = null;
        if (localksession == null) {
            runtimeManager = RuntimeManagerRegistry.get().getManager(((org.drools.core.process.instance.WorkItem) workItem).getDeploymentId());
            engine = runtimeManager.getRuntimeEngine(ProcessInstanceIdContext.get(workItem.getProcessInstanceId()));
            localksession = engine.getKieSession();
        }
        try {
            EthereumUtils.observeContractEvent(web3j,
                                               eventName,
                                               contractAddress,
                                               eventIndexedParameter,
                                               eventNonIndexedParameter,
                                               eventReturnType,
                                               localksession,
                                               signalName,
                                               doAbortOnUpdate,
                                               workItemManager,
                                               workItem);
            
        } finally {
            if (engine != null) {
                runtimeManager.disposeRuntimeEngine(engine);
            }
        }
    } catch (Exception e) {
        logger.error("Error executing workitem: " + e.getMessage());
        handleException(e);
    }
}
 
Example 14
Source File: FilterTester.java    From client-sdk-java with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
    web3jService = mock(Web3jService.class);
    web3j = Web3j.build(web3jService, 1000, scheduledExecutorService);
}
 
Example 15
Source File: JsonRpc2_0RxTest.java    From client-sdk-java with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
    web3jService = mock(Web3jService.class);
    web3j = Web3j.build(web3jService, 1000, Executors.newSingleThreadScheduledExecutor());
}
 
Example 16
Source File: RequestTest.java    From etherscan-explorer with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected void initWeb3Client(HttpService httpService) {
    web3j = Web3j.build(httpService);
}
 
Example 17
Source File: Scenario.java    From client-sdk-java with Apache License 2.0 4 votes vote down vote up
private VoteInfo createVoteInfo(String nodeHost, String nodeId, VoteOption voteOption) {
  	Web3j web3j =  Web3j.build(new HttpService(nodeHost));
  	ProposalContract voteContract = ProposalContract.load(web3j, voteCredentials, chainId);
  	return new VoteInfo(voteContract, nodeId, voteOption,web3j);
}
 
Example 18
Source File: Web3Service.java    From tutorials with MIT License 4 votes vote down vote up
public void customInit(String provider) {
    this.web3j = Web3j.build(new HttpService(provider));
}
 
Example 19
Source File: JsonRpc2_0RxTest.java    From web3j with Apache License 2.0 4 votes vote down vote up
@BeforeEach
public void setUp() {
    web3jService = mock(Web3jService.class);
    web3j = Web3j.build(web3jService, 1000, Executors.newSingleThreadScheduledExecutor());
}
 
Example 20
Source File: CreateTransactionInteract.java    From Upchain-wallet with GNU Affero General Public License v3.0 4 votes vote down vote up
public Single<String>  createERC20Transfer(ETHWallet from,  String to, String contractAddress, BigInteger amount, BigInteger gasPrice, BigInteger gasLimit, String password) {
    final Web3j web3j = Web3j.build(new HttpService(networkRepository.getDefaultNetwork().rpcServerUrl));

    String callFuncData = TokenRepository.createTokenTransferData(to, amount);


    return networkRepository.getLastTransactionNonce(web3j, from.address)
            .flatMap(nonce -> Single.fromCallable( () -> {

        Credentials credentials = WalletUtils.loadCredentials(password,  from.getKeystorePath());
        RawTransaction rawTransaction = RawTransaction.createTransaction(
                nonce, gasPrice, gasLimit, contractAddress, callFuncData);

        LogUtils.d("rawTransaction:" + rawTransaction);

        byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);

        String hexValue = Numeric.toHexString(signedMessage);
        EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).send();

        return ethSendTransaction.getTransactionHash();

    } ).subscribeOn(Schedulers.computation())
                    .observeOn(AndroidSchedulers.mainThread()));
}