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


Java Convert类代码示例

本文整理汇总了Java中org.web3j.utils.Convert的典型用法代码示例。如果您正苦于以下问题:Java Convert类的具体用法?Java Convert怎么用?Java Convert使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


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

示例1: testSendFunds

import org.web3j.utils.Convert; //导入依赖的package包/类
/**
 * Ether transfer tests using methods {@link Transfer#sendFunds()}.
 * Sending account needs to be unlocked for this to work.   
 */
@Test
public void testSendFunds() throws Exception {
	BigDecimal amountEther = BigDecimal.valueOf(0.123);
	BigInteger amountWei = Convert.toWei(amountEther, Convert.Unit.ETHER).toBigInteger();

	ensureFunds(Alice.ADDRESS, amountWei);

	BigInteger fromBalanceBefore = getBalanceWei(Alice.ADDRESS);
	BigInteger toBalanceBefore = getBalanceWei(Bob.ADDRESS);

	// this is the method to test here
	TransactionReceipt txReceipt = Transfer.sendFunds(
			web3j, Alice.CREDENTIALS, Bob.ADDRESS, amountEther, Convert.Unit.ETHER);

	BigInteger txFees = txReceipt.getGasUsed().multiply(Web3jConstants.GAS_PRICE);

	assertFalse(txReceipt.getBlockHash().isEmpty());
	assertEquals("Unexected balance for 'from' address", fromBalanceBefore.subtract(amountWei.add(txFees)), getBalanceWei(Alice.ADDRESS));
	assertEquals("Unexected balance for 'to' address", toBalanceBefore.add(amountWei), getBalanceWei(Bob.ADDRESS));
}
 
开发者ID:matthiaszimmermann,项目名称:web3j_demo,代码行数:25,代码来源:TransferEtherTest.java

示例2: testCreateAccountFromScratch

import org.web3j.utils.Convert; //导入依赖的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

示例3: refill

import org.web3j.utils.Convert; //导入依赖的package包/类
public void refill(BigDecimal minBalance, String address, Supplier<TransactionManager> managerSupplier) throws InterruptedException, ExecutionException {
    BigDecimal balance = ethereumService.getBalance(address, Convert.Unit.ETHER);

    log.info("Balance of {} is {}", address, balance);

    if (minBalance != null && minBalance.signum() > 0) {
        if (balance.compareTo(minBalance) < 0) {
            TransactionManager manager = managerSupplier.get();
            log.info("Refill {} ETH from {} to {}", minBalance, manager.getFromAddress(), address);
            try {
                new Transfer(web3j, manager).sendFunds(address, minBalance, Convert.Unit.ETHER).send();
            } catch (Exception e) {
                log.warn("Refill failed", e);
            }
            log.info("Balance after refill of {} is {}", address, ethereumService.getBalance(address, Convert.Unit.ETHER));
        }
    }
}
 
开发者ID:papyrusglobal,项目名称:state-channels,代码行数:19,代码来源:BalanceRefillService.java

示例4: run

import org.web3j.utils.Convert; //导入依赖的package包/类
/**
 * Transfers 0.123 Ethers from the coinbase account to the client's second account.
 */
@Override
public void run() throws Exception {
	super.run();
	
	// get basic info 
	EthMining mining = web3j.ethMining().sendAsync().get();
	EthCoinbase coinbase = web3j.ethCoinbase().sendAsync().get();
	EthAccounts accounts = web3j.ethAccounts().sendAsync().get();

	System.out.println("Client is mining: " + mining.getResult());
	System.out.println("Coinbase address: " + coinbase.getAddress());
	System.out.println("Coinbase balance: " + Web3jUtils.getBalanceEther(web3j, coinbase.getAddress()) + "\n");
	
	// get addresses and amount to transfer
	String fromAddress = coinbase.getAddress();
	String toAddress = accounts.getResult().get(1);
	BigInteger amountWei = Convert.toWei("0.123", Convert.Unit.ETHER).toBigInteger();

	// do the transfer
	demoTransfer(fromAddress, toAddress, amountWei);
}
 
开发者ID:matthiaszimmermann,项目名称:web3j_demo,代码行数:25,代码来源:TransferDemo.java

示例5: performTransfer

import org.web3j.utils.Convert; //导入依赖的package包/类
private TransactionReceipt performTransfer(
        Web3j web3j, String destinationAddress, Credentials credentials,
        BigDecimal amountInWei) {

    console.printf("Commencing transfer (this may take a few minutes) ");
    try {
        Future<TransactionReceipt> future = Transfer.sendFunds(
                web3j, credentials, destinationAddress, amountInWei, Convert.Unit.WEI)
                .sendAsync();

        while (!future.isDone()) {
            console.printf(".");
            Thread.sleep(500);
        }
        console.printf("$%n%n");
        return future.get();
    } catch (InterruptedException | ExecutionException | TransactionException | IOException e) {
        exitError("Problem encountered transferring funds: \n" + e.getMessage());
    }
    throw new RuntimeException("Application exit failure");
}
 
开发者ID:web3j,项目名称:web3j,代码行数:22,代码来源:WalletSendFunds.java

示例6: getBalance

import org.web3j.utils.Convert; //导入依赖的package包/类
public BigDecimal getBalance(String accountAddress, Convert.Unit unit) {
    try {
        BigInteger balance = web3j.ethGetBalance(accountAddress, DefaultBlockParameterName.LATEST).send().getBalance();
        return Convert.fromWei(new BigDecimal(balance), unit);
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}
 
开发者ID:papyrusglobal,项目名称:state-channels,代码行数:9,代码来源:EthereumService.java

示例7: transfer

import org.web3j.utils.Convert; //导入依赖的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

示例8: init

import org.web3j.utils.Convert; //导入依赖的package包/类
@PostConstruct
private void init() {
  String clientConfig = CONFIG.getPropertyValue(EthereumClientProperty.class);
  if (StringUtility.compareIgnoreCase(EthereumClientCodeType.TestRpcCode.ID, clientConfig) == 0) {
    m_useTestrpc = true;
  }

  // move some initial funds to alice's account (only when working with testrpc)
  if (m_useTestrpc) {
    try {
      EthCoinbase coinbase = getWeb3j().ethCoinbase().sendAsync().get();
      String from = coinbase.getAddress();
      BigDecimal balance = getBalance(from);
      LOG.info("coinbase: " + from + ", balance: " + balance.toString());
      rpc_coinbase = from;

      String contractOwnerAdress = Alice.ADDRESS;
      if (getBalance(contractOwnerAdress).compareTo(Convert.toWei("10", Convert.Unit.ETHER)) < 0) {
        transferEther(rpc_coinbase, contractOwnerAdress, Convert.toWei("10", Convert.Unit.ETHER).toBigInteger());
      }

    }
    catch (Exception e) {
      LOG.error(e.getMessage());
      e.printStackTrace();
    }
  }
}
 
开发者ID:BSI-Business-Systems-Integration-AG,项目名称:trading-network,代码行数:29,代码来源:EthereumService.java

示例9: getBalance

import org.web3j.utils.Convert; //导入依赖的package包/类
public BigDecimal getBalance(String address, Unit unit) {
  if (address == null || unit == null) {
    return null;
  }

  BigInteger balance = getBalanceWei(address);

  if (balance == null) {
    return null;
  }

  return Convert.fromWei(new BigDecimal(balance), unit);
}
 
开发者ID:BSI-Business-Systems-Integration-AG,项目名称:trading-network,代码行数:14,代码来源:EthereumService.java

示例10: addRow

import org.web3j.utils.Convert; //导入依赖的package包/类
private void addRow(String txId, Transaction tx, TransactionTablePageData pageData) {
  TransactionTableRowData rowData = pageData.addRow();
  rowData.setId(txId);
  rowData.setFrom(tx.getFromAddress());
  rowData.setTo(tx.getToAddress());
  BigDecimal valueEther = Convert.fromWei(new BigDecimal(tx.getValue()), Unit.ETHER);
  rowData.setValue(valueEther);
  rowData.setStatus(tx.getStatus());
  rowData.setHash(tx.getHash());
  if (CompareUtility.isOneOf(CONFIG.getPropertyValue(EthereumClientProperty.class), EthereumClientCodeType.MainNetCode.ID, EthereumClientCodeType.TestnetCode.ID) &&
      tx.getStatus() > TransactionStatusLookupCall.OFFLINE
      && StringUtility.hasText(tx.getHash())) {
    StringBuilder url = new StringBuilder("https://");
    if (EthereumClientCodeType.TestnetCode.ID.equals(CONFIG.getPropertyValue(EthereumClientProperty.class))) {
      url.append("rinkeby.");
    }
    url.append("etherscan.io/tx/");
    url.append(tx.getHash());
    rowData.setTrackingUrl(url.toString());
  }
  TransactionReceipt receipt = tx.getTransactionReceipt();
  if (receipt != null) {
    try {
      rowData.setBlock(receipt.getBlockNumber().longValue());
    }
    catch (Exception e) {
      LOG.info("failed to fetch tx block number", e);
    }
  }
}
 
开发者ID:BSI-Business-Systems-Integration-AG,项目名称:trading-network,代码行数:31,代码来源:TransactionService.java

示例11: onTransactionReceived

import org.web3j.utils.Convert; //导入依赖的package包/类
public void onTransactionReceived(Transaction tx) {
    BigInteger wei = tx.getValue();
    BigDecimal ether = Convert.fromWei(new BigDecimal(tx.getValue()), Convert.Unit.ETHER);
    String to = tx.getTo();
    String hash = tx.getHash();
    String from = tx.getFrom();

    if (addressMap.containsKey(tx.getTo())) {
        // credito
        System.out.println("Se ha recibido su depósito de " + ether + " ether enviado a su cuenta " + to + " enviado por " + from + " tx " + hash);
    } else if (addressMap.containsKey(tx.getFrom())) {
        //debito
        System.out.println("Se ha hecho un retiro de " + ether + " ether desde su cuenta " + to + " hacia la cuenta destino " + from + " tx " + hash);
    }
}
 
开发者ID:jestevez,项目名称:ethereum-java-wallet,代码行数:16,代码来源:EthereumWallet.java

示例12: sendCoins

import org.web3j.utils.Convert; //导入依赖的package包/类
public TransactionReceipt sendCoins(Credentials credentials, String toAddress, BigDecimal value) throws Exception {
    try {
        TransactionReceipt transactionReceipt = Transfer.sendFunds(web3j, credentials, toAddress, value, Convert.Unit.ETHER);
        //BigInteger gas = transactionReceipt.getGasUsed();
        //String transactionHash1 = transactionReceipt.getTransactionHash();
        return transactionReceipt;
    } catch (Exception ex) {
        throw ex;
    }
}
 
开发者ID:jestevez,项目名称:ethereum-java-wallet,代码行数:11,代码来源:EthereumWallet.java

示例13: testTransfer

import org.web3j.utils.Convert; //导入依赖的package包/类
@Test
public void testTransfer() throws Exception {
    TransactionReceipt transactionReceipt = Transfer.sendFunds(
            web3j, ALICE, BOB.getAddress(), BigDecimal.valueOf(0.2), Convert.Unit.ETHER)
            .send();
    assertFalse(transactionReceipt.getBlockHash().isEmpty());
}
 
开发者ID:web3j,项目名称:web3j,代码行数:8,代码来源:SendEtherIT.java

示例14: createTransaction

import org.web3j.utils.Convert; //导入依赖的package包/类
private static RawTransaction createTransaction() {
    BigInteger value = Convert.toWei("1", Convert.Unit.ETHER).toBigInteger();

    return RawTransaction.createEtherTransaction(
            BigInteger.valueOf(1048587), BigInteger.valueOf(500000), BigInteger.valueOf(500000),
            "0x9C98E381Edc5Fe1Ac514935F3Cc3eDAA764cf004",
            value);
}
 
开发者ID:web3j,项目名称:web3j,代码行数:9,代码来源:SignTransactionIT.java

示例15: run

import org.web3j.utils.Convert; //导入依赖的package包/类
private void run(String walletFileLocation, String destinationAddress) {
    File walletFile = new File(walletFileLocation);
    Credentials credentials = getCredentials(walletFile);
    console.printf("Wallet for address " + credentials.getAddress() + " loaded\n");

    if (!WalletUtils.isValidAddress(destinationAddress)
            && !EnsResolver.isValidEnsName(destinationAddress)) {
        exitError("Invalid destination address specified");
    }

    Web3j web3j = getEthereumClient();

    BigDecimal amountToTransfer = getAmountToTransfer();
    Convert.Unit transferUnit = getTransferUnit();
    BigDecimal amountInWei = Convert.toWei(amountToTransfer, transferUnit);

    confirmTransfer(amountToTransfer, transferUnit, amountInWei, destinationAddress);

    TransactionReceipt transactionReceipt = performTransfer(
            web3j, destinationAddress, credentials, amountInWei);

    console.printf("Funds have been successfully transferred from %s to %s%n"
                    + "Transaction hash: %s%nMined block number: %s%n",
            credentials.getAddress(),
            destinationAddress,
            transactionReceipt.getTransactionHash(),
            transactionReceipt.getBlockNumber());
}
 
开发者ID:web3j,项目名称:web3j,代码行数:29,代码来源:WalletSendFunds.java


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