Java Code Examples for org.web3j.protocol.core.methods.response.EthSendTransaction#getTransactionHash()

The following examples show how to use org.web3j.protocol.core.methods.response.EthSendTransaction#getTransactionHash() . 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: HumanStandardTokenIT.java    From etherscan-explorer with GNU General Public License v3.0 6 votes vote down vote up
private String execute(
        Credentials credentials, Function function, String contractAddress) throws Exception {
    BigInteger nonce = getNonce(credentials.getAddress());

    String encodedFunction = FunctionEncoder.encode(function);

    RawTransaction rawTransaction = RawTransaction.createTransaction(
            nonce,
            GAS_PRICE,
            GAS_LIMIT,
            contractAddress,
            encodedFunction);

    byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
    String hexValue = Numeric.toHexString(signedMessage);

    EthSendTransaction transactionResponse = web3j.ethSendRawTransaction(hexValue)
            .sendAsync().get();

    return transactionResponse.getTransactionHash();
}
 
Example 3
Source File: CreateRawTransactionIT.java    From etherscan-explorer with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testTransferEther() throws Exception {
    BigInteger nonce = getNonce(ALICE.getAddress());
    RawTransaction rawTransaction = createEtherTransaction(
            nonce, BOB.getAddress());

    byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, ALICE);
    String hexValue = Numeric.toHexString(signedMessage);

    EthSendTransaction ethSendTransaction =
            web3j.ethSendRawTransaction(hexValue).sendAsync().get();
    String transactionHash = ethSendTransaction.getTransactionHash();

    assertFalse(transactionHash.isEmpty());

    TransactionReceipt transactionReceipt =
            waitForTransactionReceipt(transactionHash);

    assertThat(transactionReceipt.getTransactionHash(), is(transactionHash));
}
 
Example 4
Source File: PrivateTransactionManager.java    From web3j with Apache License 2.0 5 votes vote down vote up
private TransactionReceipt processResponse(final EthSendTransaction transactionResponse)
        throws IOException, TransactionException {
    if (transactionResponse.hasError()) {
        throw new RuntimeException(
                "Error processing transaction request: "
                        + transactionResponse.getError().getMessage());
    }

    final String transactionHash = transactionResponse.getTransactionHash();

    return transactionReceiptProcessor.waitForTransactionReceipt(transactionHash);
}
 
Example 5
Source File: TransactionManager.java    From web3j with Apache License 2.0 5 votes vote down vote up
private TransactionReceipt processResponse(EthSendTransaction transactionResponse)
        throws IOException, TransactionException {
    if (transactionResponse.hasError()) {
        throw new RuntimeException(
                "Error processing transaction request: "
                        + transactionResponse.getError().getMessage());
    }

    String transactionHash = transactionResponse.getTransactionHash();

    return transactionReceiptProcessor.waitForTransactionReceipt(transactionHash);
}
 
Example 6
Source File: AsfWeb3jImpl.java    From asf-sdk with GNU General Public License v3.0 5 votes vote down vote up
private String successOrThrow(EthSendTransaction ethSendTransaction)
    throws TransactionFailedException {
  if (ethSendTransaction.getError() != null) {
    throw new TransactionFailedException(ethSendTransaction.getError()
        .getMessage());
  } else {
    return ethSendTransaction.getTransactionHash();
  }
}
 
Example 7
Source File: EthereumNetworkManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected RawTransactionResponse doInBackground(Void... params) {
    BigInteger nonce = getNonce();
    RawTransaction rawTransaction;
    String blockNumber = getBlocNumber();
    byte[] signedMessage;
    if (TextUtils.isEmpty(contractData)) {
        rawTransaction = RawTransaction.createEtherTransaction(nonce, gasPrice, gasLimit, toAddress, value);
    } else {
        rawTransaction = RawTransaction.createTransaction(nonce, gasPrice, gasLimit, toAddress, new String(Hex.encode(contractData.getBytes())));
    }



    if (walletManager.getCredentials() != null && rawTransaction != null) {
        signedMessage = TransactionEncoder.signMessage(rawTransaction, walletManager.getCredentials());
    } else {
        return null;
    }

    String hexValue = Numeric.toHexString(signedMessage);
    EthSendTransaction ethSendTransaction = null;


    try {
        ethSendTransaction = web3jConnection.ethSendRawTransaction(hexValue).send();
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (ethSendTransaction != null && ethSendTransaction.getTransactionHash() != null) {
        return new RawTransactionResponse(ethSendTransaction.getTransactionHash(),
                hexValue, blockNumber);
    } else {
        return null;
    }
}
 
Example 8
Source File: EthereumNetworkManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected RawTransactionResponse doInBackground(Void... params) {
    BigInteger nonce = getNonce();
    if (nonce == null) return null;
    RawTransaction rawTransaction;
    String blockNumber = getBlocNumber();
    if (TextUtils.isEmpty(contractData)) {
        rawTransaction = RawTransaction.createEtherTransaction(nonce, gasPrice, gasLimit, toAddress, value);
    } else {
        rawTransaction = RawTransaction.createTransaction(nonce, gasPrice, gasLimit, toAddress, new String(Hex.encode(contractData.getBytes())));
    }

    byte[] signedMessage;
    if (walletManager.getCredentials() != null && rawTransaction != null) {
        signedMessage = TransactionEncoder.signMessage(rawTransaction, walletManager.getCredentials());
    } else {
        return null;
    }

    String hexValue = Numeric.toHexString(signedMessage);
    EthSendTransaction ethSendTransaction = null;


        try {
            ethSendTransaction = web3jConnection.ethSendRawTransaction(hexValue).send();
        } catch (IOException e) {
            e.printStackTrace();
        }

    if (ethSendTransaction != null && ethSendTransaction.getTransactionHash() != null) {
        return new RawTransactionResponse(ethSendTransaction.getTransactionHash(),
                hexValue, blockNumber);
    } else {
        return null;
    }
}
 
Example 9
Source File: EthereumNetworkManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected RawTransactionResponse doInBackground(Void... params) {
    BigInteger nonce = getNonce();
    RawTransaction rawTransaction;
    String blockNumber = getBlockNumber();
    byte[] signedMessage;
    if (TextUtils.isEmpty(contractData)) {
        rawTransaction = RawTransaction.createEtherTransaction(nonce, gasPrice, gasLimit, toAddress, value);
    } else {
        rawTransaction = RawTransaction.createTransaction(nonce, gasPrice, gasLimit, toAddress, new String(Hex.encode(contractData.getBytes())));
    }



    if (walletManager.getCredentials() != null && rawTransaction != null) {
        signedMessage = TransactionEncoder.signMessage(rawTransaction, walletManager.getCredentials());
    } else {
        return null;
    }

    String hexValue = Numeric.toHexString(signedMessage);
    EthSendTransaction ethSendTransaction = null;


    try {
        ethSendTransaction = web3jConnection.ethSendRawTransaction(hexValue).send();
    } catch (IOException e) {
        e.printStackTrace();
        Log.d("psd", e.toString());
    }

    if (ethSendTransaction != null && ethSendTransaction.getTransactionHash() != null) {
        return new RawTransactionResponse(ethSendTransaction.getTransactionHash(),
                hexValue, blockNumber);
    } else {
        return null;
    }
}
 
Example 10
Source File: HumanStandardTokenIT.java    From web3j with Apache License 2.0 5 votes vote down vote up
private String sendCreateContractTransaction(Credentials credentials, BigInteger initialSupply)
        throws Exception {
    BigInteger nonce = getNonce(credentials.getAddress());

    String encodedConstructor =
            FunctionEncoder.encodeConstructor(
                    Arrays.asList(
                            new Uint256(initialSupply),
                            new Utf8String("web3j tokens"),
                            new Uint8(BigInteger.TEN),
                            new Utf8String("w3j$")));

    RawTransaction rawTransaction =
            RawTransaction.createContractTransaction(
                    nonce,
                    GAS_PRICE,
                    GAS_LIMIT,
                    BigInteger.ZERO,
                    getHumanStandardTokenBinary() + encodedConstructor);

    byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
    String hexValue = Numeric.toHexString(signedMessage);

    EthSendTransaction transactionResponse =
            web3j.ethSendRawTransaction(hexValue).sendAsync().get();

    return transactionResponse.getTransactionHash();
}
 
Example 11
Source File: BaseIntegrationTest.java    From eventeum with Apache License 2.0 5 votes vote down vote up
protected String sendTransaction() throws ExecutionException, InterruptedException, IOException {
    EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(
            CREDS.getAddress(), DefaultBlockParameterName.LATEST).sendAsync().get();
    BigInteger nonce = ethGetTransactionCount.getTransactionCount();

    final Transaction tx = Transaction.createEtherTransaction(CREDS.getAddress(),
            nonce, GAS_PRICE, GAS_LIMIT, ZERO_ADDRESS, BigInteger.ONE);

    EthSendTransaction response = web3j.ethSendTransaction(tx).send();

    return response.getTransactionHash();
}
 
Example 12
Source File: TransactionManager.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
private TransactionReceipt processResponse(EthSendTransaction transactionResponse)
        throws IOException, TransactionException {
    if (transactionResponse.hasError()) {
        throw new RuntimeException("Error processing transaction request: "
                + transactionResponse.getError().getMessage());
    }

    String transactionHash = transactionResponse.getTransactionHash();

    return transactionReceiptProcessor.waitForTransactionReceipt(transactionHash);
}
 
Example 13
Source File: AbstractEthereumTest.java    From web3j_demo with Apache License 2.0 5 votes vote down vote up
String transferWei(String from, String to, BigInteger amountWei) throws Exception {
	BigInteger nonce = getNonce(from);
	Transaction transaction = Transaction.createEtherTransaction(
			from, nonce, Web3jConstants.GAS_PRICE, Web3jConstants.GAS_LIMIT_ETHER_TX, to, amountWei);

	EthSendTransaction ethSendTransaction = web3j.ethSendTransaction(transaction).sendAsync().get();
	System.out.println("transferEther. nonce: " + nonce + " amount: " + amountWei + " to: " + to);

	String txHash = ethSendTransaction.getTransactionHash(); 
	waitForReceipt(txHash);
	
	return txHash;
}
 
Example 14
Source File: RawTransactionManager.java    From web3j with Apache License 2.0 5 votes vote down vote up
public EthSendTransaction signAndSend(RawTransaction rawTransaction) throws IOException {
    String hexValue = sign(rawTransaction);
    EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).send();

    if (ethSendTransaction != null && !ethSendTransaction.hasError()) {
        String txHashLocal = Hash.sha3(hexValue);
        String txHashRemote = ethSendTransaction.getTransactionHash();
        if (!txHashVerifier.verify(txHashLocal, txHashRemote)) {
            throw new TxHashMismatchException(txHashLocal, txHashRemote);
        }
    }

    return ethSendTransaction;
}
 
Example 15
Source File: EthSendRawTransactionTransaction.java    From besu with Apache License 2.0 5 votes vote down vote up
@Override
public String execute(final NodeRequests node) {
  try {
    EthSendTransaction response = node.eth().ethSendRawTransaction(transactionData).send();
    assertThat(response.getTransactionHash()).isNotNull();
    return response.getTransactionHash();
  } catch (final IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example 16
Source File: Eea.java    From ethsigner with Apache License 2.0 5 votes vote down vote up
public String sendTransaction(final PrivateTransaction transaction) throws IOException {
  final EthSendTransaction response =
      requestFactory
          .createRequest(
              "eea_sendTransaction", singletonList(transaction), EthSendTransaction.class)
          .send();

  assertThat(response.getTransactionHash()).isNotEmpty();
  assertThat(response.getError()).isNull();

  return response.getTransactionHash();
}
 
Example 17
Source File: SendEtherIT.java    From web3j with Apache License 2.0 4 votes vote down vote up
@Test
public void testTransferEther() throws Exception {
    unlockAccount();

    BigInteger nonce = getNonce(ALICE.getAddress());
    BigInteger value = Convert.toWei("0.5", Convert.Unit.ETHER).toBigInteger();

    Transaction transaction =
            Transaction.createEtherTransaction(
                    ALICE.getAddress(), nonce, GAS_PRICE, GAS_LIMIT, BOB.getAddress(), value);

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

    String transactionHash = ethSendTransaction.getTransactionHash();

    assertFalse(transactionHash.isEmpty());

    TransactionReceipt transactionReceipt = waitForTransactionReceipt(transactionHash);

    assertEquals(transactionReceipt.getTransactionHash(), (transactionHash));
}
 
Example 18
Source File: TransferDemo.java    From web3j_demo with Apache License 2.0 4 votes vote down vote up
/**
 * Implementation of the Ethers transfer.
 * <ol>
 *   <li>Get nonce for for the sending account</li>
 *   <li>Create the transaction object</li>
 *   <li>Send the transaction to the network</li>
 *   <li>Wait for the confirmation</li>
 * </ol>
 */
void demoTransfer(String fromAddress, String toAddress, BigInteger amountWei)
		throws Exception
{
	System.out.println("Accounts[1] (to address) " + toAddress + "\n" + 
			"Balance before Tx: " + Web3jUtils.getBalanceEther(web3j, toAddress) + "\n");

	System.out.println("Transfer " + Web3jUtils.weiToEther(amountWei) + " Ether to account");

	// step 1: get the nonce (tx count for sending address)
	EthGetTransactionCount transactionCount = web3j
			.ethGetTransactionCount(fromAddress, DefaultBlockParameterName.LATEST)
			.sendAsync()
			.get();

	BigInteger nonce = transactionCount.getTransactionCount();
	System.out.println("Nonce for sending address (coinbase): " + nonce);

	// step 2: create the transaction object
	Transaction transaction = Transaction
			.createEtherTransaction(
					fromAddress, 
					nonce, 
					Web3jConstants.GAS_PRICE, 
					Web3jConstants.GAS_LIMIT_ETHER_TX, 
					toAddress, 
					amountWei);

	// step 3: send the tx to the network
	EthSendTransaction response = web3j
			.ethSendTransaction(transaction)
			.sendAsync()
			.get();

	String txHash = response.getTransactionHash();		
	System.out.println("Tx hash: " + txHash);

	// step 4: wait for the confirmation of the network
	TransactionReceipt receipt = Web3jUtils.waitForReceipt(web3j, txHash);
	
	BigInteger gasUsed = receipt.getCumulativeGasUsed();
	System.out.println("Tx cost: " + gasUsed + " Gas (" + 
			Web3jUtils.weiToEther(gasUsed.multiply(Web3jConstants.GAS_PRICE)) +" Ether)\n");

	System.out.println("Balance after Tx: " + Web3jUtils.getBalanceEther(web3j, toAddress));
}
 
Example 19
Source File: TransferEtherTest.java    From web3j_demo with Apache License 2.0 4 votes vote down vote up
/**
 * Ether transfer tests using methods {@link Transaction#createEtherTransaction()}, and {@link Web3j#ethSendTransaction()}.
 * Sending account needs to be unlocked for this to work.   
 */
@Test
public void testCreateAndSendTransaction() throws Exception {

	String from = getCoinbase();
	BigInteger nonce = getNonce(from);
	String to = Alice.ADDRESS;
	BigInteger amountWei = Convert.toWei("0.456", Convert.Unit.ETHER).toBigInteger();

	// this is the method to test here
	Transaction transaction = Transaction
			.createEtherTransaction(
					from, 
					nonce, 
					Web3jConstants.GAS_PRICE, 
					Web3jConstants.GAS_LIMIT_ETHER_TX, 
					to, 
					amountWei);
	

	// record account balances before the transfer
	BigInteger fromBalanceBefore = getBalanceWei(from);
	BigInteger toBalanceBefore = getBalanceWei(to);

	// send the transaction to the ethereum client
	EthSendTransaction ethSendTx = web3j
			.ethSendTransaction(transaction)
			.sendAsync()
			.get();

	String txHash = ethSendTx.getTransactionHash();
	assertFalse(txHash.isEmpty());
	
	TransactionReceipt txReceipt = waitForReceipt(txHash);
	BigInteger txFee = txReceipt.getCumulativeGasUsed().multiply(Web3jConstants.GAS_PRICE);

	// coinbase might have gotten additional funds from mining
	BigInteger fromMinimumBalanceExpected = fromBalanceBefore.subtract(amountWei.add(txFee));
	BigInteger fromBalanceActual = getBalanceWei(from);
	BigInteger fromBalanceDelta = fromBalanceActual.subtract(fromMinimumBalanceExpected);
	
	System.out.println("testCreateAndSendTransaction balance difference=" + fromBalanceDelta + " likely cause block reward (5 Ethers) and tx fees (" + txFee + " Weis)");
	assertTrue("Unexected balance for 'from' address. difference=" + fromBalanceDelta, fromBalanceDelta.signum() >= 0);
	assertEquals("Unexected balance for 'to' address", toBalanceBefore.add(amountWei), getBalanceWei(to));		
}
 
Example 20
Source File: CreateAccountTest.java    From web3j_demo with Apache License 2.0 4 votes vote down vote up
@Test
public void testCreateAccountFromScratch() throws Exception {
	
	// create new private/public key pair
	ECKeyPair keyPair = Keys.createEcKeyPair();
	
	BigInteger publicKey = keyPair.getPublicKey();
	String publicKeyHex = Numeric.toHexStringWithPrefix(publicKey);
	
	BigInteger privateKey = keyPair.getPrivateKey();
	String privateKeyHex = Numeric.toHexStringWithPrefix(privateKey);
	
	// create credentials + address from private/public key pair
	Credentials credentials = Credentials.create(new ECKeyPair(privateKey, publicKey));
	String address = credentials.getAddress();
	
	// print resulting data of new account
	System.out.println("private key: '" + privateKeyHex + "'");
	System.out.println("public key: '" + publicKeyHex + "'");
	System.out.println("address: '" + address + "'\n");
	
	// test (1) check if it's possible to transfer funds to new address
	BigInteger amountWei = Convert.toWei("0.131313", Convert.Unit.ETHER).toBigInteger();
	transferWei(getCoinbase(), address, amountWei);

	BigInteger balanceWei = getBalanceWei(address);
	BigInteger nonce = getNonce(address);
	
	assertEquals("Unexpected nonce for 'to' address", BigInteger.ZERO, nonce);
	assertEquals("Unexpected balance for 'to' address", amountWei, balanceWei);

	// test (2) funds can be transferred out of the newly created account
	BigInteger txFees = Web3jConstants.GAS_LIMIT_ETHER_TX.multiply(Web3jConstants.GAS_PRICE);
	RawTransaction txRaw = RawTransaction
			.createEtherTransaction(
					nonce, 
					Web3jConstants.GAS_PRICE, 
					Web3jConstants.GAS_LIMIT_ETHER_TX, 
					getCoinbase(), 
					amountWei.subtract(txFees));

	// sign raw transaction using the sender's credentials
	byte[] txSignedBytes = TransactionEncoder.signMessage(txRaw, credentials);
	String txSigned = Numeric.toHexString(txSignedBytes);

	// send the signed transaction to the ethereum client
	EthSendTransaction ethSendTx = web3j
			.ethSendRawTransaction(txSigned)
			.sendAsync()
			.get();

	Error error = ethSendTx.getError();
	String txHash = ethSendTx.getTransactionHash();
	assertNull(error);		
	assertFalse(txHash.isEmpty());
	
	waitForReceipt(txHash);

	assertEquals("Unexpected nonce for 'to' address", BigInteger.ONE, getNonce(address));
	assertTrue("Balance for 'from' address too large: " + getBalanceWei(address), getBalanceWei(address).compareTo(txFees) < 0);
}