Java Code Examples for org.web3j.protocol.core.DefaultBlockParameter#valueOf()

The following examples show how to use org.web3j.protocol.core.DefaultBlockParameter#valueOf() . 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: PollingBlockSubscriptionStrategy.java    From eventeum with Apache License 2.0 6 votes vote down vote up
@Override
public Disposable subscribe() {

    final Optional<LatestBlock> latestBlock = getLatestBlock();

    if (latestBlock.isPresent()) {
        final DefaultBlockParameter blockParam = DefaultBlockParameter.valueOf(latestBlock.get().getNumber());

        blockSubscription = web3j.replayPastAndFutureBlocksFlowable(blockParam, true)
                .subscribe(block -> { triggerListeners(block); });

    } else {
        blockSubscription = web3j.blockFlowable(true).subscribe(block -> {
            triggerListeners(block);
        });
    }

    return blockSubscription;
}
 
Example 2
Source File: PubSubBlockSubscriptionStrategy.java    From eventeum with Apache License 2.0 6 votes vote down vote up
@Override
public Disposable subscribe() {
    final Optional<LatestBlock> latestBlock = getLatestBlock();

    if (latestBlock.isPresent()) {
        final DefaultBlockParameter blockParam = DefaultBlockParameter.valueOf(latestBlock.get().getNumber());

        //New heads can only start from latest block so we need to obtain missing blocks first
        blockSubscription = web3j.replayPastBlocksFlowable(blockParam, true)
                .doOnComplete(() -> blockSubscription = subscribeToNewHeads())
                .subscribe(ethBlock -> triggerListeners(convertToEventeumBlock(ethBlock)));
    } else {
        blockSubscription = subscribeToNewHeads();
    }

    return blockSubscription;
}
 
Example 3
Source File: DepositFetcher.java    From teku with Apache License 2.0 6 votes vote down vote up
private SafeFuture<List<DepositContract.DepositEventEventResponse>>
    getDepositEventsInRangeFromContract(BigInteger fromBlockNumber, BigInteger toBlockNumber) {

  DefaultBlockParameter fromBlock = DefaultBlockParameter.valueOf(fromBlockNumber);
  DefaultBlockParameter toBlock = DefaultBlockParameter.valueOf(toBlockNumber);

  return depositContract
      .depositEventInRange(fromBlock, toBlock)
      .exceptionallyCompose(
          (err) -> {
            LOG.debug(
                "Failed to request deposit events for block numbers in the range ({}, {}). Retrying.",
                fromBlockNumber,
                toBlockNumber,
                err);

            return asyncRunner.runAfterDelay(
                () -> getDepositEventsInRangeFromContract(fromBlockNumber, toBlockNumber),
                Constants.ETH1_DEPOSIT_REQUEST_RETRY_TIMEOUT,
                TimeUnit.SECONDS);
          });
}
 
Example 4
Source File: CliqueConditions.java    From besu with Apache License 2.0 5 votes vote down vote up
public Condition validatorsAtBlockHashFromBlockNumberEqual(
    final Node node, final long blockNumber, final BesuNode... validators) {
  final DefaultBlockParameter blockParameter =
      DefaultBlockParameter.valueOf(BigInteger.valueOf(blockNumber));
  final String blockHash = node.execute(eth.block(blockParameter)).getHash();
  return new ExpectValidatorsAtBlockHash(
      clique, fromHexString(blockHash), validatorAddresses(validators));
}
 
Example 5
Source File: Web3jEth1Provider.java    From teku with Apache License 2.0 5 votes vote down vote up
@Override
public SafeFuture<EthBlock.Block> getEth1Block(final UnsignedLong blockNumber) {
  LOG.trace("Getting eth1 block {}", blockNumber);
  DefaultBlockParameter blockParameter =
      DefaultBlockParameter.valueOf(blockNumber.bigIntegerValue());
  return getEth1Block(blockParameter);
}
 
Example 6
Source File: RequestTest.java    From web3j with Apache License 2.0 5 votes vote down vote up
@Test
public void testClicqueGetSigners() throws Exception {
    final DefaultBlockParameter blockParameter = DefaultBlockParameter.valueOf("latest");
    web3j.cliqueGetSigners(blockParameter).send();

    verifyResult(
            "{\"jsonrpc\":\"2.0\",\"method\":\"clique_getSigners\","
                    + "\"params\":[\"latest\"],\"id\":1}");
}
 
Example 7
Source File: RequestTest.java    From web3j with Apache License 2.0 5 votes vote down vote up
@Test
public void testIbftGetValidatorsByBlockNumber() throws Exception {
    final DefaultBlockParameter blockParameter = DefaultBlockParameter.valueOf("latest");
    web3j.ibftGetValidatorsByBlockNumber(blockParameter).send();

    verifyResult(
            "{\"jsonrpc\":\"2.0\",\"method\":\"ibft_getValidatorsByBlockNumber\","
                    + "\"params\":[\"latest\"],\"id\":1}");
}
 
Example 8
Source File: EventUtils.java    From alpha-wallet-android with MIT License 4 votes vote down vote up
public EthFilter generateLogFilter(EventDefinition ev, Token originToken, AttributeInterface attrIf) throws Exception
{
    int chainId = ev.contract.addresses.keySet().iterator().next();
    String eventContractAddr = ev.contract.addresses.get(chainId).get(0);

    final Event resolverEvent = generateEventFunction(ev);
    //work out which topics to filter on
    String filterTopic = ev.getFilterTopicIndex();
    String filterTopicValue = ev.getFilterTopicValue();

    //find the topic index - at this stage we only handle single topics
    int topicIndex = ev.getTopicIndex(filterTopic);

    //isolate which indexed param it is
    List<String> indexedParams = ev.eventModule.getArgNames(true);

    DefaultBlockParameter startBlock = DefaultBlockParameterName.EARLIEST;

    if (ev.readBlock != null && ev.readBlock.compareTo(BigInteger.ZERO) > 0)
    {
        startBlock = DefaultBlockParameter.valueOf(ev.readBlock);
    }

    final org.web3j.protocol.core.methods.request.EthFilter filter =
            new org.web3j.protocol.core.methods.request.EthFilter(
                    startBlock,
                    DefaultBlockParameterName.LATEST,
                    eventContractAddr)                            // contract address
                    .addSingleTopic(EventEncoder.encode(resolverEvent)); // event name

    for (int i = 0; i < indexedParams.size(); i++)
    {
        if (i == topicIndex)
        {
            addTopicFilter(ev, filter, filterTopicValue, originToken, eventContractAddr, attrIf); //add the required log filter - allowing for multiple tokenIds
            break;
        }
        else
        {
            filter.addSingleTopic(null);
        }
    }

    return filter;
}
 
Example 9
Source File: TransferEtherTest.java    From web3j_demo with Apache License 2.0 4 votes vote down vote up
/**
 * Test accessing transactions, blocks and their attributes using methods {@link Web3j#ethGetTransactionByHash()},  {@link Web3j#ethGetBlockByHash()}  {@link Web3j#ethGetBlockByNumber()}.
 */
@Test
public void testTransactionAndBlockAttributes() throws Exception {
	String account0 = getCoinbase();
	String account1 = getAccount(1);
	BigInteger transferAmount = new BigInteger("31415926");

	String txHash = transferWei(account0, account1, transferAmount);
	waitForReceipt(txHash);

	// query for tx via tx hash value
	EthTransaction ethTx = web3j
			.ethGetTransactionByHash(txHash)
			.sendAsync()
			.get();

	org.web3j.protocol.core.methods.response.Transaction tx = ethTx
			.getTransaction()
			.get();

	String blockHash = tx.getBlockHash();
	BigInteger blockNumber = tx.getBlockNumber();
	String from = tx.getFrom();
	String to = tx.getTo();
	BigInteger amount = tx.getValue();

	// check tx attributes
	assertTrue("Tx hash does not match input hash", txHash.equals(tx.getHash()));
	assertTrue("Tx block index invalid", blockNumber == null || blockNumber.compareTo(new BigInteger("0")) >= 0);
	assertTrue("Tx from account does not match input account", account0.equals(from));
	assertTrue("Tx to account does not match input account", account1.equals(to));
	assertTrue("Tx transfer amount does not match input amount", transferAmount.equals(amount));

	// query for block by hash
	EthBlock ethBlock = web3j
			.ethGetBlockByHash(blockHash, true)
			.sendAsync()
			.get();

	Block blockByHash = ethBlock.getBlock(); 
	assertNotNull(String.format("Failed to get block for hash %s", blockHash), blockByHash);
	System.out.println("Got block for hash " + blockHash);


	// query for block by number
	DefaultBlockParameter blockParameter = DefaultBlockParameter
			.valueOf(blockNumber);

	ethBlock = web3j
			.ethGetBlockByNumber(blockParameter, true)
			.sendAsync()
			.get();
	
	Block blockByNumber = ethBlock.getBlock(); 
	assertNotNull(String.format("Failed to get block for number %d", blockNumber), blockByNumber);
	System.out.println("Got block for number " + blockNumber);

	assertTrue("Bad tx hash for block by number", blockByNumber.getHash().equals(blockHash));
	assertTrue("Bad tx number for block by hash", blockByHash.getNumber().equals(blockNumber));
	assertTrue("Query block by hash and number have different parent hashes", blockByHash.getParentHash().equals(blockByNumber.getParentHash()));
	assertTrue("Query block by hash and number results in different blocks", blockByHash.equals(blockByNumber));

	// find original tx in block
	boolean found = false;
	for(TransactionResult<?> txResult: blockByHash.getTransactions()) {
		TransactionObject txObject = (TransactionObject) txResult;

		// verify tx attributes returned by block query
		if(txObject.getHash().equals(txHash)) {
			assertTrue("Tx from block has bad from", txObject.getFrom().equals(account0));
			assertTrue("Tx from block has bad to", txObject.getTo().equals(account1));
			assertTrue("Tx from block has bad amount", txObject.getValue().equals(transferAmount));
			found = true;
			break;
		}
	}

	assertTrue("Tx not found in blocks transaction list", found);
}