org.web3j.protocol.core.DefaultBlockParameter Java Examples

The following examples show how to use org.web3j.protocol.core.DefaultBlockParameter. 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: EthGetBalanceAtBlockTransaction.java    From besu with Apache License 2.0 6 votes vote down vote up
@Override
public BigInteger execute(final NodeRequests node) {
  try {
    final EthGetBalance result =
        node.eth()
            .ethGetBalance(account.getAddress(), DefaultBlockParameter.valueOf(block))
            .send();
    assertThat(result).isNotNull();
    assertThat(result.hasError()).isFalse();

    return result.getBalance();

  } catch (final IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example #2
Source File: JsonRpc2_0Rx.java    From etherscan-explorer with GNU General Public License v3.0 6 votes vote down vote up
private Observable<EthBlock> replayBlocksObservableSync(
        DefaultBlockParameter startBlock, DefaultBlockParameter endBlock,
        boolean fullTransactionObjects, boolean ascending) {

    BigInteger startBlockNumber = null;
    BigInteger endBlockNumber = null;
    try {
        startBlockNumber = getBlockNumber(startBlock);
        endBlockNumber = getBlockNumber(endBlock);
    } catch (IOException e) {
        Observable.error(e);
    }

    if (ascending) {
        return Observables.range(startBlockNumber, endBlockNumber)
                .flatMap(i -> web3j.ethGetBlockByNumber(
                        new DefaultBlockParameterNumber(i),
                        fullTransactionObjects).observable());
    } else {
        return Observables.range(startBlockNumber, endBlockNumber, false)
                .flatMap(i -> web3j.ethGetBlockByNumber(
                        new DefaultBlockParameterNumber(i),
                        fullTransactionObjects).observable());
    }
}
 
Example #3
Source File: RequestTest.java    From web3j with Apache License 2.0 6 votes vote down vote up
@Test
public void testPrivCall() throws Exception {
    web3j.privCall(
                    MOCK_PRIVACY_GROUP_ID.toString(),
                    Transaction.createEthCallTransaction(
                            "0xa70e8dd61c5d32be8058bb8eb970870f07233155",
                            "0xb60e8dd61c5d32be8058bb8eb970870f07233155",
                            "0x0"),
                    DefaultBlockParameter.valueOf("latest"))
            .send();

    verifyResult(
            "{\"jsonrpc\":\"2.0\",\"method\":\"priv_call\","
                    + "\"params\":[\"DyAOiF/ynpc+JXa2YAGB0bCitSlOMNm+ShmB/7M6C4w=\",{\"from\":\"0xa70e8dd61c5d32be8058bb8eb970870f07233155\","
                    + "\"to\":\"0xb60e8dd61c5d32be8058bb8eb970870f07233155\",\"data\":\"0x0\"},"
                    + "\"latest\"],\"id\":1}");
}
 
Example #4
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 #5
Source File: ENS.java    From etherscan-explorer with GNU General Public License v3.0 6 votes vote down vote up
public Observable<NewTTLEventResponse> newTTLEventObservable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) {
    final Event event = new Event("NewTTL", 
            Arrays.<TypeReference<?>>asList(new TypeReference<Bytes32>() {}),
            Arrays.<TypeReference<?>>asList(new TypeReference<Uint64>() {}));
    EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress());
    filter.addSingleTopic(EventEncoder.encode(event));
    return web3j.ethLogObservable(filter).map(new Func1<Log, NewTTLEventResponse>() {
        @Override
        public NewTTLEventResponse call(Log log) {
            EventValues eventValues = extractEventParameters(event, log);
            NewTTLEventResponse typedResponse = new NewTTLEventResponse();
            typedResponse.node = (byte[]) eventValues.getIndexedValues().get(0).getValue();
            typedResponse.ttl = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue();
            return typedResponse;
        }
    });
}
 
Example #6
Source File: JsonRpc2_0Parity.java    From etherscan-explorer with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Request<?, ParityAddressesResponse> parityListAccounts(
        BigInteger quantity, String accountId, DefaultBlockParameter blockParameter) {
    if (blockParameter == null) {
        return new Request<>(
                "parity_listAccounts",
                Arrays.asList(quantity, accountId),
                web3jService,
                ParityAddressesResponse.class);
    } else {
        return new Request<>(
                "parity_listAccounts",
                Arrays.asList(quantity, accountId, blockParameter),
                web3jService,
                ParityAddressesResponse.class);
    }
}
 
Example #7
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 #8
Source File: JsonRpc2_0Rx.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
private Observable<PlatonBlock> replayBlocksObservableSync(
        DefaultBlockParameter startBlock, DefaultBlockParameter endBlock,
        boolean fullTransactionObjects, boolean ascending) {

    BigInteger startBlockNumber = null;
    BigInteger endBlockNumber = null;
    try {
        startBlockNumber = getBlockNumber(startBlock);
        endBlockNumber = getBlockNumber(endBlock);
    } catch (IOException e) {
        Observable.error(e);
    }

    if (ascending) {
        return Observables.range(startBlockNumber, endBlockNumber)
                .flatMap(i -> web3j.platonGetBlockByNumber(
                        new DefaultBlockParameterNumber(i),
                        fullTransactionObjects).observable());
    } else {
        return Observables.range(startBlockNumber, endBlockNumber, false)
                .flatMap(i -> web3j.platonGetBlockByNumber(
                        new DefaultBlockParameterNumber(i),
                        fullTransactionObjects).observable());
    }
}
 
Example #9
Source File: EthereumMetadata.java    From presto-ethereum with Apache License 2.0 6 votes vote down vote up
private long findBlockByTimestamp(long timestamp, long offset) throws IOException {
    long startBlock = 1L;
    long currentBlock = web3j.ethBlockNumber().send().getBlockNumber().longValue();

    if (currentBlock <= 1) {
        return currentBlock;
    }

    long low = startBlock;
    long high = currentBlock;
    long middle = low + (high - low) / 2;

    while(low <= high) {
        middle = low + (high - low) / 2;
        long ts = web3j.ethGetBlockByNumber(DefaultBlockParameter.valueOf(BigInteger.valueOf(middle)), false).send().getBlock().getTimestamp().longValue();

        if (ts < timestamp) {
            low = middle + 1;
        } else if (ts > timestamp) {
            high = middle - 1;
        } else {
            return middle;
        }
    }
    return middle + offset;
}
 
Example #10
Source File: PublicResolver.java    From etherscan-explorer with GNU General Public License v3.0 6 votes vote down vote up
public Observable<ContentChangedEventResponse> contentChangedEventObservable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) {
    final Event event = new Event("ContentChanged", 
            Arrays.<TypeReference<?>>asList(new TypeReference<Bytes32>() {}),
            Arrays.<TypeReference<?>>asList(new TypeReference<Bytes32>() {}));
    EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress());
    filter.addSingleTopic(EventEncoder.encode(event));
    return web3j.ethLogObservable(filter).map(new Func1<Log, ContentChangedEventResponse>() {
        @Override
        public ContentChangedEventResponse call(Log log) {
            EventValues eventValues = extractEventParameters(event, log);
            ContentChangedEventResponse typedResponse = new ContentChangedEventResponse();
            typedResponse.node = (byte[]) eventValues.getIndexedValues().get(0).getValue();
            typedResponse.hash = (byte[]) eventValues.getNonIndexedValues().get(0).getValue();
            return typedResponse;
        }
    });
}
 
Example #11
Source File: JsonRpc2_0Rx.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
public Observable<PlatonBlock> catchUpToLatestAndSubscribeToNewBlocksObservable(
        DefaultBlockParameter startBlock, boolean fullTransactionObjects,
        long pollingInterval) {

    return catchUpToLatestBlockObservable(
            startBlock, fullTransactionObjects,
            blockObservable(fullTransactionObjects, pollingInterval));
}
 
Example #12
Source File: JsonRpc2_0Besu.java    From web3j with Apache License 2.0 5 votes vote down vote up
@Override
public Request<?, EthAccounts> cliqueGetSigners(DefaultBlockParameter defaultBlockParameter) {
    return new Request<>(
            "clique_getSigners",
            Arrays.asList(defaultBlockParameter.getValue()),
            web3jService,
            EthAccounts.class);
}
 
Example #13
Source File: JsonRpc2_0Rx.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
private Observable<PlatonBlock> catchUpToLatestBlockObservableSync(
        DefaultBlockParameter startBlock, boolean fullTransactionObjects,
        Observable<PlatonBlock> onCompleteObservable) {

    BigInteger startBlockNumber;
    BigInteger latestBlockNumber;
    try {
        startBlockNumber = getBlockNumber(startBlock);
        latestBlockNumber = getLatestBlockNumber();
    } catch (IOException e) {
        return Observable.error(e);
    }

    if (startBlockNumber.compareTo(latestBlockNumber) > -1) {
        return onCompleteObservable;
    } else {
        return Observable.concat(
                replayBlocksObservableSync(
                        new DefaultBlockParameterNumber(startBlockNumber),
                        new DefaultBlockParameterNumber(latestBlockNumber),
                        fullTransactionObjects),
                Observable.defer(() -> catchUpToLatestBlockObservableSync(
                        new DefaultBlockParameterNumber(latestBlockNumber.add(BigInteger.ONE)),
                        fullTransactionObjects,
                        onCompleteObservable)));
    }
}
 
Example #14
Source File: JsonRpc2_0Rx.java    From web3j with Apache License 2.0 5 votes vote down vote up
public Flowable<EthBlock> replayBlocksFlowable(
        DefaultBlockParameter startBlock,
        DefaultBlockParameter endBlock,
        boolean fullTransactionObjects,
        boolean ascending) {
    // We use a scheduler to ensure this Flowable runs asynchronously for users to be
    // consistent with the other Flowables
    return replayBlocksFlowableSync(startBlock, endBlock, fullTransactionObjects, ascending)
            .subscribeOn(scheduler);
}
 
Example #15
Source File: JsonRpc2_0Besu.java    From web3j with Apache License 2.0 5 votes vote down vote up
@Override
public Request<?, EthCall> privCall(
        String privacyGroupId,
        final Transaction transaction,
        final DefaultBlockParameter defaultBlockParameter) {
    return new Request<>(
            "priv_call",
            Arrays.asList(privacyGroupId, transaction, defaultBlockParameter),
            web3jService,
            org.web3j.protocol.core.methods.response.EthCall.class);
}
 
Example #16
Source File: Web3jService.java    From eventeum with Apache License 2.0 5 votes vote down vote up
@Override
public String getRevertReason(String from, String to, BigInteger blockNumber, String input) {
    try {
        return web3j.ethCall(
                Transaction.createEthCallTransaction(from, to, input),
                DefaultBlockParameter.valueOf(blockNumber)
        ).send().getRevertReason();
    } catch (IOException e) {
        throw new BlockchainException("Error getting the revert reason", e);
    }
}
 
Example #17
Source File: RequestTest.java    From web3j with Apache License 2.0 5 votes vote down vote up
@Test
public void testParityListAccountsNoAccountOffsetWithBlockTag() throws Exception {
    BigInteger maxQuantityReturned = BigInteger.valueOf(100);
    DefaultBlockParameter blockParameter = new DefaultBlockParameterNumber(BigInteger.ONE);
    web3j.parityListAccounts(maxQuantityReturned, null, blockParameter).send();

    verifyResult(
            "{\"jsonrpc\":\"2.0\",\"method\":\"parity_listAccounts\","
                    + "\"params\":[100,null,\"0x1\"],\"id\":1}");
}
 
Example #18
Source File: ClientTransactionManager.java    From web3j with Apache License 2.0 5 votes vote down vote up
@Override
public String sendCall(String to, String data, DefaultBlockParameter defaultBlockParameter)
        throws IOException {
    EthCall ethCall =
            web3j.ethCall(
                            Transaction.createEthCallTransaction(getFromAddress(), to, data),
                            defaultBlockParameter)
                    .send();

    assertCallNotReverted(ethCall);
    return ethCall.getValue();
}
 
Example #19
Source File: Web3jServiceTest.java    From eventeum with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetRevertReason() throws IOException {
    final Request<?, EthCall> mockRequest = mock(Request.class);
    final EthCall ethCall = mock(EthCall.class);

    when(ethCall.getRevertReason()).thenReturn(REVERT_REASON);
    when(mockRequest.send()).thenReturn(ethCall);
    doReturn(mockRequest).when(mockWeb3j).ethCall(any(Transaction.class), any(DefaultBlockParameter.class));

    assertEquals(REVERT_REASON, underTest.getRevertReason(FROM_ADDRESS, TO_ADDRESS, BLOCK_NUMBER, "0x1"));
}
 
Example #20
Source File: PlatonFilter.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
public PlatonFilter(DefaultBlockParameter fromBlock, DefaultBlockParameter toBlock,
                    List<String> address) {
    super();
    this.fromBlock = fromBlock;
    this.toBlock = toBlock;
    this.address = address;
}
 
Example #21
Source File: DepositContract.java    From teku with Apache License 2.0 5 votes vote down vote up
public SafeFuture<List<DepositEventEventResponse>> depositEventInRange(
    DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) {
  final EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress());
  filter.addSingleTopic(EventEncoder.encode(DEPOSITEVENT_EVENT));
  return SafeFuture.of(
      web3j
          .ethGetLogs(filter)
          .sendAsync()
          .thenApply(
              logs ->
                  logs.getLogs().stream()
                      .map(log -> (Log) log.get())
                      .map(this::convertLogToDepositEventEventResponse)
                      .collect(Collectors.toList())));
}
 
Example #22
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 #23
Source File: JsonRpc2_0Rx.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
private BigInteger getBlockNumber(
        DefaultBlockParameter defaultBlockParameter) throws IOException {
    if (defaultBlockParameter instanceof DefaultBlockParameterNumber) {
        return ((DefaultBlockParameterNumber) defaultBlockParameter).getBlockNumber();
    } else {
        EthBlock latestEthBlock = web3j.ethGetBlockByNumber(
                defaultBlockParameter, false).send();
        return latestEthBlock.getBlock().getNumber();
    }
}
 
Example #24
Source File: EthFilter.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
public EthFilter(DefaultBlockParameter fromBlock, DefaultBlockParameter toBlock,
                 List<String> address) {
    super();
    this.fromBlock = fromBlock;
    this.toBlock = toBlock;
    this.address = address;
}
 
Example #25
Source File: Web3jEth1Provider.java    From teku with Apache License 2.0 5 votes vote down vote up
@Override
public SafeFuture<EthCall> ethCall(
    final String from, String to, String data, final UnsignedLong blockNumber) {
  return SafeFuture.of(
      web3j
          .ethCall(
              Transaction.createEthCallTransaction(from, to, data),
              DefaultBlockParameter.valueOf(blockNumber.bigIntegerValue()))
          .sendAsync());
}
 
Example #26
Source File: JsonRpc2_0Besu.java    From web3j with Apache License 2.0 5 votes vote down vote up
@Override
public Request<?, EthGetCode> privGetCode(
        final String privacyGroupId,
        final String address,
        final DefaultBlockParameter defaultBlockParameter) {
    ArrayList<String> result =
            new ArrayList<>(
                    Arrays.asList(privacyGroupId, address, defaultBlockParameter.getValue()));
    return new Request<>("priv_getCode", result, web3jService, EthGetCode.class);
}
 
Example #27
Source File: JsonRpc2_0Rx.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
public Observable<EthBlock> replayBlocksObservable(
        DefaultBlockParameter startBlock, DefaultBlockParameter endBlock,
        boolean fullTransactionObjects, boolean ascending) {
    // We use a scheduler to ensure this Observable runs asynchronously for users to be
    // consistent with the other Observables
    return replayBlocksObservableSync(startBlock, endBlock, fullTransactionObjects, ascending)
            .subscribeOn(scheduler);
}
 
Example #28
Source File: JsonRpc2_0Rx.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
public Observable<EthBlock> catchUpToLatestBlockObservable(
        DefaultBlockParameter startBlock, boolean fullTransactionObjects,
        Observable<EthBlock> onCompleteObservable) {
    // We use a scheduler to ensure this Observable runs asynchronously for users to be
    // consistent with the other Observables
    return catchUpToLatestBlockObservableSync(
            startBlock, fullTransactionObjects, onCompleteObservable)
            .subscribeOn(scheduler);
}
 
Example #29
Source File: ENS.java    From web3j with Apache License 2.0 4 votes vote down vote up
public Flowable<NewResolverEventResponse> newResolverEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) {
    EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress());
    filter.addSingleTopic(EventEncoder.encode(NEWRESOLVER_EVENT));
    return newResolverEventFlowable(filter);
}
 
Example #30
Source File: EthFilter.java    From etherscan-explorer with GNU General Public License v3.0 4 votes vote down vote up
public EthFilter(DefaultBlockParameter fromBlock, DefaultBlockParameter toBlock,
                 String address) {
    this(fromBlock, toBlock, Arrays.asList(address));
}