当前位置: 首页>>代码示例>>Java>>正文


Java EthSendTransaction.getTransactionHash方法代码示例

本文整理汇总了Java中org.web3j.protocol.core.methods.response.EthSendTransaction.getTransactionHash方法的典型用法代码示例。如果您正苦于以下问题:Java EthSendTransaction.getTransactionHash方法的具体用法?Java EthSendTransaction.getTransactionHash怎么用?Java EthSendTransaction.getTransactionHash使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.web3j.protocol.core.methods.response.EthSendTransaction的用法示例。


在下文中一共展示了EthSendTransaction.getTransactionHash方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: testCreateAccountFromScratch

import org.web3j.protocol.core.methods.response.EthSendTransaction; //导入方法依赖的package包/类
@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);
}
 
开发者ID:matthiaszimmermann,项目名称:web3j_demo,代码行数:62,代码来源:CreateAccountTest.java

示例2: execute

import org.web3j.protocol.core.methods.response.EthSendTransaction; //导入方法依赖的package包/类
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();
}
 
开发者ID:web3j,项目名称:web3j,代码行数:22,代码来源:HumanStandardTokenIT.java

示例3: doSendTransaction

import org.web3j.protocol.core.methods.response.EthSendTransaction; //导入方法依赖的package包/类
public SentTransaction doSendTransaction(FunctionCall call, BigInteger value, TransactionParams params) throws IOException {
    RawTransaction rawTransaction = RawTransaction.createTransaction(
        params.getNonce(),
        params.getGasPrice(),
        params.getGasLimit(),
        call.contractAddress,
        value,
        call.data
    );

    boolean success = false;
    try {
        EthSendTransaction transaction = signAndSend(rawTransaction);
        CallUtil.checkError(transaction);
        success = true;
        return new SentTransaction(transaction.getTransactionHash(), params);
    } finally {
        if (!success) this.nonce = BigInteger.valueOf(-1);
    }
}
 
开发者ID:papyrusglobal,项目名称:state-channels,代码行数:21,代码来源:ThreadsafeTransactionManager.java

示例4: transferFromCoinbaseAndWait

import org.web3j.protocol.core.methods.response.EthSendTransaction; //导入方法依赖的package包/类
/**
 * 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);
}
 
开发者ID:matthiaszimmermann,项目名称:web3j_demo,代码行数:29,代码来源:Web3jUtils.java

示例5: testTransferEther

import org.web3j.protocol.core.methods.response.EthSendTransaction; //导入方法依赖的package包/类
@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));
}
 
开发者ID:web3j,项目名称:web3j,代码行数:21,代码来源:CreateRawTransactionIT.java

示例6: testDeploySmartContract

import org.web3j.protocol.core.methods.response.EthSendTransaction; //导入方法依赖的package包/类
@Test
public void testDeploySmartContract() throws Exception {
    BigInteger nonce = getNonce(ALICE.getAddress());
    RawTransaction rawTransaction = createSmartContractTransaction(nonce);

    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));

    assertFalse("Contract execution ran out of gas",
            rawTransaction.getGasLimit().equals(transactionReceipt.getGasUsed()));
}
 
开发者ID:web3j,项目名称:web3j,代码行数:23,代码来源:CreateRawTransactionIT.java

示例7: deployContract

import org.web3j.protocol.core.methods.response.EthSendTransaction; //导入方法依赖的package包/类
public Address deployContract(TransactionManager transactionManager, String binary, Map<String, Address> libraries, Type... constructorArgs) throws IOException, InterruptedException, TransactionException {
    ContractLinker linker = new ContractLinker(binary);
    if (libraries != null && !libraries.isEmpty()) {
        libraries.forEach(linker::link);
    }
    linker.assertLinked();
    String encodedConstructor = FunctionEncoder.encodeConstructor(Arrays.<Type>asList(constructorArgs));
    String data = linker.getBinary() + encodedConstructor;

    EthSendTransaction transactionResponse = transactionManager.sendTransaction(
        properties.getGasPrice(), properties.getGasLimit(), null, data, BigInteger.ZERO);

    if (transactionResponse.hasError()) {
        throw new RuntimeException("Error processing transaction request: "
            + transactionResponse.getError().getMessage());
    }

    String transactionHash = transactionResponse.getTransactionHash();

    Optional<TransactionReceipt> receiptOptional =
        sendTransactionReceiptRequest(transactionHash, web3j);

    long millis = properties.getSleep().toMillis();
    int attempts = properties.getAttempts();
    for (int i = 0; i < attempts; i++) {
        if (!receiptOptional.isPresent()) {
            Thread.sleep(millis);
            receiptOptional = sendTransactionReceiptRequest(transactionHash, web3j);
        } else {
            String contractAddress = receiptOptional.get().getContractAddress();
            return new Address(contractAddress);
        }
    }
    throw new TransactionException("Transaction receipt was not generated after " + (millis * attempts / 1000)
        + " seconds for transaction: " + transactionHash);
}
 
开发者ID:papyrusglobal,项目名称:state-channels,代码行数:37,代码来源:DeployService.java

示例8: transferWei

import org.web3j.protocol.core.methods.response.EthSendTransaction; //导入方法依赖的package包/类
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;
}
 
开发者ID:matthiaszimmermann,项目名称:web3j_demo,代码行数:14,代码来源:AbstractEthereumTest.java

示例9: transfer

import org.web3j.protocol.core.methods.response.EthSendTransaction; //导入方法依赖的package包/类
public static String transfer(String from, String to, int amount, Unit unit) throws InterruptedException, ExecutionException {
	BigInteger nonce = getNonce(from);
	BigInteger weiAmount = Convert.toWei(BigDecimal.valueOf(amount), unit).toBigInteger();
	Transaction transaction = new Transaction(from, nonce, GAS_PRICE_DEFAULT, GAS_LIMIT_DEFAULT, to, weiAmount, null);
	EthSendTransaction txRequest = getWeb3j().ethSendTransaction(transaction).sendAsync().get();
	return txRequest.getTransactionHash();
}
 
开发者ID:BSI-Business-Systems-Integration-AG,项目名称:trading-network,代码行数:8,代码来源:Web3jHelper.java

示例10: transferEther

import org.web3j.protocol.core.methods.response.EthSendTransaction; //导入方法依赖的package包/类
private String transferEther(String from, String to, BigInteger amount) throws Exception {
  BigInteger nonce = getNonce(from);

  org.web3j.protocol.core.methods.request.Transaction transaction = new org.web3j.protocol.core.methods.request.Transaction(from, nonce, GAS_PRICE_DEFAULT, GAS_LIMIT_DEFAULT, to, amount, null);
  EthSendTransaction txRequest = getWeb3j().ethSendTransaction(transaction).sendAsync().get();
  String txHash = txRequest.getTransactionHash();

  System.out.println("tx hash: " + txHash);
  System.out.println(String.format("amount: %d from: %s to %s", amount, from, to));

  return txHash;
}
 
开发者ID:BSI-Business-Systems-Integration-AG,项目名称:trading-network,代码行数:13,代码来源:EthereumService.java

示例11: sendCreateContractTransaction

import org.web3j.protocol.core.methods.response.EthSendTransaction; //导入方法依赖的package包/类
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();
}
 
开发者ID:web3j,项目名称:web3j,代码行数:28,代码来源:HumanStandardTokenIT.java

示例12: processResponse

import org.web3j.protocol.core.methods.response.EthSendTransaction; //导入方法依赖的package包/类
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);
}
 
开发者ID:web3j,项目名称:web3j,代码行数:12,代码来源:TransactionManager.java

示例13: demoTransfer

import org.web3j.protocol.core.methods.response.EthSendTransaction; //导入方法依赖的package包/类
/**
 * 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));
}
 
开发者ID:matthiaszimmermann,项目名称:web3j_demo,代码行数:55,代码来源:TransferDemo.java

示例14: testCreateAndSendTransaction

import org.web3j.protocol.core.methods.response.EthSendTransaction; //导入方法依赖的package包/类
/**
 * 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));		
}
 
开发者ID:matthiaszimmermann,项目名称:web3j_demo,代码行数:49,代码来源:TransferEtherTest.java

示例15: testCreateSignAndSendTransaction

import org.web3j.protocol.core.methods.response.EthSendTransaction; //导入方法依赖的package包/类
/**
 * Ether transfer tests using methods {@link RawTransaction#createEtherTransaction()}, {@link TransactionEncoder#signMessage()} and {@link Web3j#ethSendRawTransaction()}.
 * Most complex transfer mechanism, but offers the highest flexibility.   
 */
@Test
public void testCreateSignAndSendTransaction() throws Exception {

	String from = Alice.ADDRESS;
	Credentials credentials = Alice.CREDENTIALS;
	BigInteger nonce = getNonce(from);
	String to = Bob.ADDRESS; 
	BigInteger amountWei = Convert.toWei("0.789", Convert.Unit.ETHER).toBigInteger();

	// create raw transaction
	RawTransaction txRaw = RawTransaction
			.createEtherTransaction(
					nonce, 
					Web3jConstants.GAS_PRICE, 
					Web3jConstants.GAS_LIMIT_ETHER_TX, 
					to, 
					amountWei);

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

	BigInteger txFeeEstimate = Web3jConstants.GAS_LIMIT_ETHER_TX.multiply(Web3jConstants.GAS_PRICE);

	// make sure sender has sufficient funds
	ensureFunds(Alice.ADDRESS, amountWei.add(txFeeEstimate));

	// record balanances before the ether transfer
	BigInteger fromBalanceBefore = getBalanceWei(Alice.ADDRESS);
	BigInteger toBalanceBefore = getBalanceWei(Bob.ADDRESS);

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

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

	assertEquals("Unexected balance for 'from' address", fromBalanceBefore.subtract(amountWei.add(txFee)), getBalanceWei(from));
	assertEquals("Unexected balance for 'to' address", toBalanceBefore.add(amountWei), getBalanceWei(to));
}
 
开发者ID:matthiaszimmermann,项目名称:web3j_demo,代码行数:54,代码来源:TransferEtherTest.java


注:本文中的org.web3j.protocol.core.methods.response.EthSendTransaction.getTransactionHash方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。