org.web3j.protocol.core.DefaultBlockParameterName Java Examples

The following examples show how to use org.web3j.protocol.core.DefaultBlockParameterName. 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: TransactionRepository.java    From ETHWallet with GNU General Public License v3.0 6 votes vote down vote up
public Single<String> createTransaction(Wallet from, String toAddress, BigInteger subunitAmount, BigInteger gasPrice, BigInteger gasLimit, String data, String password) {
    final Web3j web3j = Web3jFactory.build(new HttpService(networkRepository.getDefaultNetwork().rpcServerUrl));

    return Single.fromCallable(() -> {
        EthGetTransactionCount ethGetTransactionCount = web3j
                .ethGetTransactionCount(from.getAddress(), 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 #2
Source File: TokenRepository.java    From alpha-wallet-android with MIT License 6 votes vote down vote up
private String callSmartContractFunction(
        Function function, String contractAddress, NetworkInfo network, Wallet wallet) throws Exception
{
    try
    {
        String encodedFunction = FunctionEncoder.encode(function);

        org.web3j.protocol.core.methods.request.Transaction transaction
                = createEthCallTransaction(wallet.address, contractAddress, encodedFunction);
        EthCall response = getService(network.chainId).ethCall(transaction, DefaultBlockParameterName.LATEST).send();

        return response.getValue();
    }
    catch (InterruptedIOException|UnknownHostException e)
    {
        //expected to happen when user switches wallets
        return "0x";
    }
}
 
Example #3
Source File: TokenRepository.java    From alpha-wallet-android with MIT License 6 votes vote down vote up
/**
 * Call smart contract function on custom network contract. This would be used for things like ENS lookup
 * Currently because it's tied to a mainnet contract address there's no circumstance it would work
 * outside of mainnet. Users may be confused if their namespace doesn't work, even if they're currently
 * using testnet.
 *
 * @param function
 * @param contractAddress
 * @param wallet
 * @return
 */
private String callCustomNetSmartContractFunction(
        Function function, String contractAddress, Wallet wallet, int chainId)  {
    String encodedFunction = FunctionEncoder.encode(function);

    try
    {
        org.web3j.protocol.core.methods.request.Transaction transaction
                = createEthCallTransaction(wallet.address, contractAddress, encodedFunction);
        EthCall response = getService(chainId).ethCall(transaction, DefaultBlockParameterName.LATEST).send();

        return response.getValue();
    }
    catch (Exception e)
    {
        e.printStackTrace();
        return null;
    }
}
 
Example #4
Source File: Contract.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * Check that the contract deployed at the address associated with this smart contract wrapper
 * is in fact the contract you believe it is.
 *
 * <p>This method uses the
 * <a href="https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getcode">eth_getCode</a> method
 * to get the contract byte code and validates it against the byte code stored in this smart
 * contract wrapper.
 *
 * @return true if the contract is valid
 * @throws IOException if unable to connect to web3j node
 */
public boolean isValid() throws IOException {
    if (contractAddress.equals("")) {
        throw new UnsupportedOperationException(
                "Contract binary not present, you will need to regenerate your smart "
                        + "contract wrapper with web3j v2.2.0+");
    }

    PlatonGetCode ethGetCode = web3j
            .platonGetCode(contractAddress, DefaultBlockParameterName.LATEST)
            .send();
    if (ethGetCode.hasError()) {
        return false;
    }

    String code = Numeric.cleanHexPrefix(ethGetCode.getCode());
    // There may be multiple contracts in the Solidity bytecode, hence we only check for a
    // match with a subset
    return !code.isEmpty() && contractBinary.contains(code);
}
 
Example #5
Source File: WasmContract.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * Check that the contract deployed at the address associated with this smart contract wrapper is in fact the contract you believe it is.
 *
 * <p>
 * This method uses the <a href="https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getcode">eth_getCode</a> method to get the contract byte code
 * and validates it against the byte code stored in this smart contract wrapper.
 *
 * @return true if the contract is valid
 * @throws IOException if unable to connect to web3j node
 */
public boolean isValid() throws IOException {
	if (contractAddress.equals("")) {
		throw new UnsupportedOperationException(
				"Contract binary not present, you will need to regenerate your smart contract wrapper with web3j v2.2.0+");
	}

	PlatonGetCode ethGetCode = web3j.platonGetCode(contractAddress, DefaultBlockParameterName.LATEST).send();
	if (ethGetCode.hasError()) {
		return false;
	}

	String code = Numeric.cleanHexPrefix(ethGetCode.getCode());
	// There may be multiple contracts in the Solidity bytecode, hence we only check for a
	// match with a subset
	return !code.isEmpty() && contractBinary.contains(code);
}
 
Example #6
Source File: RestrictingScenario.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 *  正常的场景:
 *  初始化账户余额
 *  创建锁仓计划(4000)
 *  获取锁仓信息(4100)
 */
@Test
public void executeScenario() throws Exception {
	//初始化账户余额
	transfer();
	BigInteger restrictingBalance = web3j.platonGetBalance(restrictingSendCredentials.getAddress(), DefaultBlockParameterName.LATEST).send().getBalance();
	assertTrue(new BigDecimal(restrictingBalance).compareTo(Convert.fromVon(transferValue, Unit.VON))>=0);
	
	//创建锁仓计划(4000)
	TransactionResponse createRestrictingPlanResponse = createRestrictingPlan();
	assertTrue(createRestrictingPlanResponse.toString(),createRestrictingPlanResponse.isStatusOk());

	//获取锁仓信息(4100)
	CallResponse<RestrictingItem> getRestrictingPlanInfoResponse = getRestrictingPlanInfo();
	assertTrue(getRestrictingPlanInfoResponse.toString(),getRestrictingPlanInfoResponse.isStatusOk());
}
 
Example #7
Source File: EnsResolver.java    From alpha-wallet-android with MIT License 6 votes vote down vote up
private String callSmartContractFunction(
        Function function, String contractAddress, int chainId) throws Exception
{
    try
    {
        String encodedFunction = FunctionEncoder.encode(function);

        org.web3j.protocol.core.methods.request.Transaction transaction
                = createEthCallTransaction(TokenscriptFunction.ZERO_ADDRESS, contractAddress, encodedFunction);
        EthCall response = TokenRepository.getWeb3jService(chainId).ethCall(transaction, DefaultBlockParameterName.LATEST).send();

        return response.getValue();
    }
    catch (InterruptedIOException | UnknownHostException e)
    {
        //expected to happen when user switches wallets
        return "0x";
    }
}
 
Example #8
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 #9
Source File: EthereumUtils.java    From jbpm-work-items with Apache License 2.0 6 votes vote down vote up
public static void observeContractEvent(Web3j web3j,
                                        String contractEventName,
                                        String contractAddress,
                                        List<TypeReference<?>> indexedParameters,
                                        List<TypeReference<?>> nonIndexedParameters,
                                        String eventReturnType,
                                        rx.functions.Action1 action1) {

    Event event = new Event(contractEventName,
                            indexedParameters,
                            nonIndexedParameters);

    EthFilter filter = new EthFilter(DefaultBlockParameterName.EARLIEST,
                                     DefaultBlockParameterName.LATEST,
                                     contractAddress);

    filter.addSingleTopic(EventEncoder.encode(event));

    Class<Type> type = (Class<Type>) AbiTypes.getType(eventReturnType);
    TypeReference<Type> typeRef = TypeReference.create(type);

    web3j.ethLogObservable(filter).subscribe(action1);
}
 
Example #10
Source File: RequestTest.java    From web3j with Apache License 2.0 6 votes vote down vote up
@Test
public void testTraceFilter() throws Exception {
    web3j.traceFilter(
                    new TraceFilter(
                            DefaultBlockParameterName.EARLIEST,
                            DefaultBlockParameterName.LATEST,
                            Collections.singletonList(
                                    "0xa9bebd4853ce06c3dc1b711bbafa1514ed5b5130"),
                            Collections.singletonList(
                                    "0xB4d9b203d8D16f41916a62DEab83389cF2b7eeCb")))
            .send();

    verifyResult(
            "{\"jsonrpc\":\"2.0\",\"method\":\"trace_filter\","
                    + "\"params\":[{\"fromBlock\":\"earliest\",\"toBlock\":\"latest\","
                    + "\"fromAddress\":[\"0xa9bebd4853ce06c3dc1b711bbafa1514ed5b5130\"],"
                    + "\"toAddress\":[\"0xB4d9b203d8D16f41916a62DEab83389cF2b7eeCb\"]}],"
                    + "\"id\":1}");
}
 
Example #11
Source File: HumanStandardTokenTest.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
public void eventListening() {
	HumanStandardToken humanStandardToken = HumanStandardToken.load(contractAddress, web3j, transactionManager, gasProvider);
	Observable<TransferEventResponse> observable = humanStandardToken.transferEventObservable(DefaultBlockParameterName.EARLIEST,
			DefaultBlockParameterName.LATEST);

	Observer<TransferEventResponse> observer = new Observer<HumanStandardToken.TransferEventResponse>() {
		@Override
		public void onNext(TransferEventResponse t) {
			logger.info("from:{}", t._from);
			logger.info("to:{}", t._to);
			logger.info("value:{}", t._value);
		}

		@Override
		public void onError(Throwable e) {

		}

		@Override
		public void onCompleted() {

		}
	};
	observable.subscribe(observer);
}
 
Example #12
Source File: SendTransaction.java    From BitcoinWallet with MIT License 5 votes vote down vote up
private BigInteger getNonce(String userAddress) {
    BigInteger nonce = BigInteger.ONE;
    try {
        Request<?, EthGetTransactionCount> rs = web3j.ethGetTransactionCount(
                userAddress, DefaultBlockParameterName.PENDING);
        EthGetTransactionCount egtc = rs.sendAsync().get();
        nonce = egtc.getTransactionCount();
    } catch (Exception e) {
        System.out.println("" + e);
    }
    return nonce;
}
 
Example #13
Source File: HumanStandardTokenIT.java    From web3j with Apache License 2.0 5 votes vote down vote up
private String callSmartContractFunction(Function function, String contractAddress)
        throws Exception {
    String encodedFunction = FunctionEncoder.encode(function);

    org.web3j.protocol.core.methods.response.EthCall response =
            web3j.ethCall(
                            Transaction.createEthCallTransaction(
                                    ALICE.getAddress(), contractAddress, encodedFunction),
                            DefaultBlockParameterName.LATEST)
                    .sendAsync()
                    .get();

    return response.getValue();
}
 
Example #14
Source File: EthereumNetworkManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public void getBalance(final String address, final Callback<BigDecimal> callback) {
    if (web3jConnection != null && connectionAvailable) {
        BalanceRequestTask task = new BalanceRequestTask(address, DefaultBlockParameterName.LATEST, callback);
        task.execute();
    } else {
        provideConnection(new ConnectionCallback() {
            @Override
            public void onFinish() {
                getBalance(address, callback);
            }
        });
    }
}
 
Example #15
Source File: Web3jService.java    From eventeum with Apache License 2.0 5 votes vote down vote up
/**
 * {inheritDoc}
 */
@Override
public FilterSubscription registerEventListener(
        ContractEventFilter eventFilter, ContractEventListener eventListener) {
    log.debug("Registering event filter for event: {}", eventFilter.getId());
    final ContractEventSpecification eventSpec = eventFilter.getEventSpecification();

    final BigInteger startBlock = getStartBlockForEventFilter(eventFilter);

    EthFilter ethFilter = new EthFilter(
            new DefaultBlockParameterNumber(startBlock),
            DefaultBlockParameterName.LATEST, eventFilter.getContractAddress());

    if (eventFilter.getEventSpecification() != null) {
        ethFilter = ethFilter.addSingleTopic(Web3jUtil.getSignature(eventSpec));
    }

    final Flowable<Log> flowable = web3j.ethLogFlowable(ethFilter);

    final Disposable sub = flowable.subscribe(theLog -> {
        asyncTaskService.execute(ExecutorNameFactory.build(EVENT_EXECUTOR_NAME, eventFilter.getNode()), () -> {
            log.debug("Dispatching log: {}", theLog);
            eventListener.onEvent(
                    eventDetailsFactory.createEventDetails(eventFilter, theLog));
        });
    });

    if (sub.isDisposed()) {
        //There was an error subscribing
        throw new BlockchainException(String.format(
                "Failed to subcribe for filter %s.  The subscription is disposed.", eventFilter.getId()));
    }

    return new FilterSubscription(eventFilter, sub, startBlock);
}
 
Example #16
Source File: EthereumNetworkManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
private BigInteger getNonce() {
    BigInteger nonce = null;
    try {
        EthGetTransactionCount txCount = web3jConnection.ethGetTransactionCount(walletManager.getWalletFriendlyAddress(),
                DefaultBlockParameterName.LATEST).send();
        nonce = txCount.getTransactionCount();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return nonce;
}
 
Example #17
Source File: EthereumNetworkManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public void getBalance(final String address, final Callback<BigDecimal> callback) {
    if (web3jConnection != null && connectionAvailable) {
        BalanceRequestTask task = new BalanceRequestTask(address, DefaultBlockParameterName.LATEST, callback);
        task.execute();
    } else {
        provideConnection(new ConnectionCallback() {
            @Override
            public void onFinish() {
                getBalance(address, callback);
            }
        });
    }
}
 
Example #18
Source File: EnsResolver.java    From web3j with Apache License 2.0 5 votes vote down vote up
boolean isSynced() throws Exception {
    EthSyncing ethSyncing = web3j.ethSyncing().send();
    if (ethSyncing.isSyncing()) {
        return false;
    } else {
        EthBlock ethBlock =
                web3j.ethGetBlockByNumber(DefaultBlockParameterName.LATEST, false).send();
        long timestamp = ethBlock.getBlock().getTimestamp().longValueExact() * 1000;

        return System.currentTimeMillis() - syncThreshold < timestamp;
    }
}
 
Example #19
Source File: RequestTest.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testParityListAccountsWithAccountOffsetWithBlockTag() throws Exception {
    BigInteger maxQuantityReturned = BigInteger.valueOf(100);
    DefaultBlockParameter blockParameter = DefaultBlockParameterName.LATEST;
    web3j.parityListAccounts(maxQuantityReturned,
            "0x407d73d8a49eeb85d32cf465507dd71d507100c1", blockParameter).send();

    //CHECKSTYLE:OFF
    verifyResult("{\"jsonrpc\":\"2.0\",\"method\":\"parity_listAccounts\","
            + "\"params\":[100,\"0x407d73d8a49eeb85d32cf465507dd71d507100c1\",\"latest\"],\"id\":1}");
    //CHECKSTYLE:ON
}
 
Example #20
Source File: BaseIntegrationTest.java    From eventeum with Apache License 2.0 5 votes vote down vote up
protected BigInteger getNonce() throws ExecutionException, InterruptedException {
    final EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(
            CREDS.getAddress(), DefaultBlockParameterName.LATEST).sendAsync().get();

    final BigInteger nonce = ethGetTransactionCount.getTransactionCount();

    return nonce;
}
 
Example #21
Source File: ContractTest.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void prepareEthGetCode(String binary) throws IOException {
    EthGetCode ethGetCode = new EthGetCode();
    ethGetCode.setResult(Numeric.prependHexPrefix(binary));

    Request<?, EthGetCode> ethGetCodeRequest = mock(Request.class);
    when(ethGetCodeRequest.send())
            .thenReturn(ethGetCode);
    when(web3j.ethGetCode(ADDRESS, DefaultBlockParameterName.LATEST))
            .thenReturn((Request) ethGetCodeRequest);
}
 
Example #22
Source File: RequestTest.java    From web3j with Apache License 2.0 5 votes vote down vote up
@Test
public void testParityListAccountsWithAccountOffsetWithBlockTag() throws Exception {
    BigInteger maxQuantityReturned = BigInteger.valueOf(100);
    DefaultBlockParameter blockParameter = DefaultBlockParameterName.LATEST;
    web3j.parityListAccounts(
                    maxQuantityReturned,
                    "0x407d73d8a49eeb85d32cf465507dd71d507100c1",
                    blockParameter)
            .send();

    verifyResult(
            "{\"jsonrpc\":\"2.0\",\"method\":\"parity_listAccounts\","
                    + "\"params\":[100,\"0x407d73d8a49eeb85d32cf465507dd71d507100c1\",\"latest\"],\"id\":1}");
}
 
Example #23
Source File: EnsResolver.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
boolean isSynced() throws Exception {
    EthSyncing ethSyncing = web3j.ethSyncing().send();
    if (ethSyncing.isSyncing()) {
        return false;
    } else {
        EthBlock ethBlock =
                web3j.ethGetBlockByNumber(DefaultBlockParameterName.LATEST, false).send();
        long timestamp = ethBlock.getBlock().getTimestamp().longValueExact() * 1000;

        return System.currentTimeMillis() - syncThreshold < timestamp;
    }
}
 
Example #24
Source File: GreeterContractIT.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
private String callSmartContractFunction(
        Function function, String contractAddress) throws Exception {

    String encodedFunction = FunctionEncoder.encode(function);

    org.web3j.protocol.core.methods.response.EthCall response = web3j.ethCall(
            Transaction.createEthCallTransaction(
                    ALICE.getAddress(), contractAddress, encodedFunction),
            DefaultBlockParameterName.LATEST)
            .sendAsync().get();

    return response.getValue();
}
 
Example #25
Source File: ManagedTransactionTester.java    From web3j with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
void prepareNonceRequest() throws IOException {
    EthGetTransactionCount ethGetTransactionCount = new EthGetTransactionCount();
    ethGetTransactionCount.setResult("0x1");

    Request<?, EthGetTransactionCount> transactionCountRequest = mock(Request.class);
    when(transactionCountRequest.send()).thenReturn(ethGetTransactionCount);
    when(web3j.ethGetTransactionCount(SampleKeys.ADDRESS, DefaultBlockParameterName.PENDING))
            .thenReturn((Request) transactionCountRequest);
}
 
Example #26
Source File: EventFilterIT.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
private List<EthLog.LogResult> createFilterForEvent(
        String encodedEventSignature, String contractAddress) throws Exception {
    EthFilter ethFilter = new EthFilter(
            DefaultBlockParameterName.EARLIEST,
            DefaultBlockParameterName.LATEST,
            contractAddress
    );

    ethFilter.addSingleTopic(encodedEventSignature);

    EthLog ethLog = web3j.ethGetLogs(ethFilter).send();
    return ethLog.getLogs();
}
 
Example #27
Source File: EthereumNetworkBase.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
@Override
public Single<BigInteger> getLastTransactionNonce(Web3j web3j, String walletAddress)
{
    return Single.fromCallable(() -> {
        EthGetTransactionCount ethGetTransactionCount = web3j
                .ethGetTransactionCount(walletAddress, DefaultBlockParameterName.PENDING)
                .send();
        return ethGetTransactionCount.getTransactionCount();
    });
}
 
Example #28
Source File: DeployContractIT.java    From web3j with Apache License 2.0 5 votes vote down vote up
private String callSmartContractFunction(Function function, String contractAddress)
        throws Exception {

    String encodedFunction = FunctionEncoder.encode(function);

    org.web3j.protocol.core.methods.response.EthCall response =
            web3j.ethCall(
                            Transaction.createEthCallTransaction(
                                    ALICE.getAddress(), contractAddress, encodedFunction),
                            DefaultBlockParameterName.LATEST)
                    .sendAsync()
                    .get();

    return response.getValue();
}
 
Example #29
Source File: HumanStandardTokenIT.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
private String callSmartContractFunction(
        Function function, String contractAddress) throws Exception {
    String encodedFunction = FunctionEncoder.encode(function);

    org.web3j.protocol.core.methods.response.EthCall response = web3j.ethCall(
            Transaction.createEthCallTransaction(
                    ALICE.getAddress(), contractAddress, encodedFunction),
            DefaultBlockParameterName.LATEST)
            .sendAsync().get();

    return response.getValue();
}
 
Example #30
Source File: CreateRawTransactionIT.java    From web3j with Apache License 2.0 5 votes vote down vote up
BigInteger getNonce(String address) throws Exception {
    EthGetTransactionCount ethGetTransactionCount =
            web3j.ethGetTransactionCount(address, DefaultBlockParameterName.LATEST)
                    .sendAsync()
                    .get();

    return ethGetTransactionCount.getTransactionCount();
}