org.web3j.utils.Convert Java Examples

The following examples show how to use org.web3j.utils.Convert. 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: Transfer.java    From web3j with Apache License 2.0 6 votes vote down vote up
private TransactionReceipt send(
        String toAddress,
        BigDecimal value,
        Convert.Unit unit,
        BigInteger gasPrice,
        BigInteger gasLimit)
        throws IOException, InterruptedException, TransactionException {

    BigDecimal weiValue = Convert.toWei(value, unit);
    if (!Numeric.isIntegerValue(weiValue)) {
        throw new UnsupportedOperationException(
                "Non decimal Wei value provided: "
                        + value
                        + " "
                        + unit.toString()
                        + " = "
                        + weiValue
                        + " Wei");
    }

    String resolvedAddress = ensResolver.resolve(toAddress);
    return send(resolvedAddress, "", weiValue.toBigIntegerExact(), gasPrice, gasLimit);
}
 
Example #2
Source File: TransactionDetailsActivity.java    From guarda-android-wallets with GNU General Public License v3.0 6 votes vote down vote up
private void setValue(String respValue) {
    BigInteger value = new BigInteger(respValue);
    BigDecimal decimal = new BigDecimal(value);
    BigDecimal formatted = Convert.fromWei(decimal, Convert.Unit.ETHER);
    DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance();
    symbols.setDecimalSeparator('.');
    DecimalFormat decimalFormat = new DecimalFormat(ETH_SHOW_PATTERN_EXT, symbols);
    decimalFormat.setRoundingMode(RoundingMode.DOWN);

    String valueStr = (isDebit(walletManager.getWalletFriendlyAddress(), transaction.getTo()) ? "+" : "-")
            + " " + decimalFormat.format(formatted);
    if (transaction.getTicker() != null) {
        valueStr = valueStr + " " + transaction.getTicker();
    }
    etTrValue.setText(valueStr);
}
 
Example #3
Source File: PayWagesTest.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
public void transferToContract() throws Exception {
	String toAddress = contractAddress;

	// get balance
	PlatonGetBalance balance = web3j.platonGetBalance(toAddress, DefaultBlockParameterName.LATEST).send();
	System.err.println("Before transfer,balance >>> " + balance.getBalance().toString());

	// transfer to toAddress
	Transfer transfer = new Transfer(web3j, transactionManager);
	BigDecimal value = BigDecimal.valueOf(500L);
	TransactionReceipt receipt = transfer.sendFunds(toAddress, value, Convert.Unit.LAT, GAS_PRICE, GAS_LIMIT).send();
	System.err.println("transfer status >>> " + receipt.getStatus());
	System.err.println("transfer result >>> " + JSON.toJSONString(receipt));

	// transfer event
	PayWages payWages = PayWages.load(contractAddress, web3j, transactionManager, gasProvider);
	List<TransferEventResponse> list = payWages.getTransferEvents(receipt);
	System.err.println("to >>> " + list.get(0)._to);
	System.err.println("value >>> " + list.get(0)._value.toString());
	System.err.println("TransferEventResponse >>> " + JSON.toJSONString(list));

	// get balance
	balance = web3j.platonGetBalance(toAddress, DefaultBlockParameterName.LATEST).send();
	System.err.println("After transfer, balance >>> " + balance.getBalance().toString());
}
 
Example #4
Source File: PayWagesTest.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
public void pay() throws Exception {
	Credentials financer = WalletUtils.loadCredentials(walletPwd, financerWallet);
	transactionManager = new RawTransactionManager(web3j, financer, chainId);
	PayWages payWages = PayWages.load(contractAddress, web3j, transactionManager, gasProvider);

	BigInteger balance = payWages.getContractBalance().send();
	System.err.println("Before pay, ContractBalance >>>> " + balance);

	BigInteger amout = Convert.toVon(BigDecimal.valueOf(18), Convert.Unit.LAT).toBigInteger();
	TransactionReceipt receipt = payWages.pay(employeeAddress, amout).send();
	System.err.println("pay status >>>> " + receipt.getStatus());
	System.err.println("receipt >>>> " + JSON.toJSONString(receipt));

	balance = payWages.getContractBalance().send();
	System.err.println("After pay, ContractBalance >>>> " + balance);
}
 
Example #5
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 #6
Source File: SendingEther.java    From Android-Wallet-Token-ERC20 with Apache License 2.0 6 votes vote down vote up
@Override
protected EthSendTransaction doInBackground(String... values) {
    BigInteger ammount = Convert.toWei(values[1], Convert.Unit.ETHER).toBigInteger();
    try {

        RawTransaction rawTransaction = RawTransaction.createEtherTransaction(getNonce(), getGasPrice(), getGasLimit(), values[0], ammount);

        byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, mCredentials);
        String hexValue = "0x"+ Hex.toHexString(signedMessage);

        return mWeb3j.ethSendRawTransaction(hexValue.toString()).sendAsync().get();

    } catch (ExecutionException | InterruptedException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #7
Source File: WalletSendFunds.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
private TransactionReceipt performTransfer(
        Web3j web3j, String destinationAddress,String chainId, Credentials credentials,
        BigDecimal amountInWei) {

    console.printf("Commencing transfer (this may take a few minutes) ");
    try {
        Future<TransactionReceipt> future = Transfer.sendFunds(
                web3j, credentials, destinationAddress,chainId, amountInWei, Convert.Unit.LAT)
                .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");
}
 
Example #8
Source File: TransHistoryAdapter.java    From guarda-android-wallets with GNU General Public License v3.0 6 votes vote down vote up
private void retryTransaction(TransactionResponse item) {
    String transValue = "";
    BigInteger value = new BigInteger(item.getValue().substring(2));
    BigDecimal decimal = new BigDecimal(value);
    BigDecimal formatted = Convert.fromWei(decimal, Convert.Unit.ETHER);
    DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance();
    symbols.setDecimalSeparator('.');
    DecimalFormat decimalFormat = new DecimalFormat(ETH_SHOW_PATTERN, symbols);
    decimalFormat.setRoundingMode(RoundingMode.DOWN);
    transValue = decimalFormat.format(formatted);

    Intent intent = new Intent(context, SendingCurrencyActivity.class);
    intent.putExtra(Extras.WALLET_NUMBER, item.getTo());
    intent.putExtra(Extras.AMOUNT_TO_SEND, transValue);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);
}
 
Example #9
Source File: Amount.java    From besu with Apache License 2.0 6 votes vote down vote up
public Amount subtract(final Amount subtracting) {

    final Unit denominator;
    if (unit.getWeiFactor().compareTo(subtracting.unit.getWeiFactor()) < 0) {
      denominator = unit;
    } else {
      denominator = subtracting.unit;
    }

    final BigDecimal result =
        Convert.fromWei(
            Convert.toWei(value, unit).subtract(Convert.toWei(subtracting.value, subtracting.unit)),
            denominator);

    return new Amount(result, denominator);
  }
 
Example #10
Source File: TransHistoryAdapter.java    From guarda-android-wallets with GNU General Public License v3.0 6 votes vote down vote up
private void retryTransaction(TransactionResponse item) {
    String transValue = "";
    BigInteger value = new BigInteger(item.getValue());
    BigDecimal decimal = new BigDecimal(value);
    BigDecimal formatted = Convert.fromWei(decimal, Convert.Unit.ETHER);
    DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance();
    symbols.setDecimalSeparator('.');
    DecimalFormat decimalFormat = new DecimalFormat(ETH_SHOW_PATTERN, symbols);
    decimalFormat.setRoundingMode(RoundingMode.DOWN);
    transValue = decimalFormat.format(formatted);

    Intent intent = new Intent(context, SendingCurrencyActivity.class);
    intent.putExtra(Extras.WALLET_NUMBER, item.getTo());
    intent.putExtra(Extras.AMOUNT_TO_SEND, transValue);
    if (item.getTicker() != null) {
        intent.putExtra(Extras.TOKEN_CODE_EXTRA, item.getTicker());
    }
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);
}
 
Example #11
Source File: ConfirmationActivity.java    From alpha-wallet-android with MIT License 6 votes vote down vote up
private void onGasSettings(GasSettings gasSettings) {
    String gasPrice = BalanceUtils.weiToGwei(gasSettings.gasPrice) + " " + C.GWEI_UNIT;
    gasPriceText.setText(gasPrice);
    gasLimitText.setText(gasSettings.gasLimit.toString());

    BigDecimal networkFeeBD = new BigDecimal(gasSettings
                                                     .gasPrice.multiply(gasSettings.gasLimit));

    String networkFee = BalanceUtils.weiToEth(networkFeeBD).toPlainString() + " " + viewModel.getNetworkSymbol(chainId);
    networkFeeText.setText(networkFee);

    if (confirmationType == WEB3TRANSACTION)
    {
        //update amount
        BigDecimal ethValueBD = amount.add(networkFeeBD);

        //convert to ETH
        ethValueBD = Convert.fromWei(ethValueBD, Convert.Unit.ETHER);
        String valueUpdate = getEthString(ethValueBD.doubleValue());
        valueText.setText(valueUpdate);
    }
}
 
Example #12
Source File: ValueTransferWithAzureAcceptanceTest.java    From ethsigner with Apache License 2.0 6 votes vote down vote up
@Test
public void valueTransfer() {
  final BigInteger transferAmountWei =
      Convert.toWei("1.75", Convert.Unit.ETHER).toBigIntegerExact();
  final BigInteger startBalance = ethNode().accounts().balance(RECIPIENT);
  final Transaction transaction =
      Transaction.createEtherTransaction(
          richBenefactor().address(),
          null,
          GAS_PRICE,
          INTRINSIC_GAS,
          RECIPIENT,
          transferAmountWei);

  final String hash = ethSigner().transactions().submit(transaction);
  ethNode().transactions().awaitBlockContaining(hash);

  final BigInteger expectedEndBalance = startBalance.add(transferAmountWei);
  final BigInteger actualEndBalance = ethNode().accounts().balance(RECIPIENT);
  assertThat(actualEndBalance).isEqualTo(expectedEndBalance);
}
 
Example #13
Source File: ValueTransferWithHashicorpAcceptanceTest.java    From ethsigner with Apache License 2.0 6 votes vote down vote up
@Test
public void valueTransfer() {
  final BigInteger transferAmountWei =
      Convert.toWei("1.75", Convert.Unit.ETHER).toBigIntegerExact();
  final BigInteger startBalance = ethNode().accounts().balance(RECIPIENT);
  final Transaction transaction =
      Transaction.createEtherTransaction(
          richBenefactor().address(),
          null,
          GAS_PRICE,
          INTRINSIC_GAS,
          RECIPIENT,
          transferAmountWei);

  final String hash = ethSigner().transactions().submit(transaction);
  ethNode().transactions().awaitBlockContaining(hash);

  final BigInteger expectedEndBalance = startBalance.add(transferAmountWei);
  final BigInteger actualEndBalance = ethNode().accounts().balance(RECIPIENT);
  assertThat(actualEndBalance).isEqualTo(expectedEndBalance);
}
 
Example #14
Source File: WalletSendFunds.java    From etherscan-explorer with GNU General Public License v3.0 6 votes vote down vote up
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");
}
 
Example #15
Source File: ConnectionTimeoutAcceptanceTest.java    From ethsigner with Apache License 2.0 6 votes vote down vote up
@Test
public void submittingTransactionWithoutNonceReturnsAGatewayTimeoutError() {
  final String recipient = "0x1b00ba00ca00bb00aa00bc00be00ac00ca00da00";
  final BigInteger transferAmountWei = Convert.toWei("15.5", Unit.ETHER).toBigIntegerExact();

  final Transaction transaction =
      Transaction.createEtherTransaction(
          richBenefactor().address(),
          null,
          GAS_PRICE,
          INTRINSIC_GAS,
          recipient,
          transferAmountWei);
  final SignerResponse<JsonRpcErrorResponse> signerResponse =
      ethSigner.transactions().submitExceptional(transaction);
  assertThat(signerResponse.status()).isEqualTo(GATEWAY_TIMEOUT);
  assertThat(signerResponse.jsonRpc().getError())
      .isEqualTo(CONNECTION_TO_DOWNSTREAM_NODE_TIMED_OUT);
}
 
Example #16
Source File: ClientSideTlsAcceptanceTest.java    From ethsigner with Apache License 2.0 6 votes vote down vote up
@Test
void ethSignerDoesNotConnectToServerNotSpecifiedInTrustStore(@TempDir Path workDir)
    throws Exception {
  final TlsCertificateDefinition serverPresentedCert =
      TlsCertificateDefinition.loadFromResource("tls/cert1.pfx", "password");
  final TlsCertificateDefinition ethSignerCert =
      TlsCertificateDefinition.loadFromResource("tls/cert2.pfx", "password2");
  final TlsCertificateDefinition ethSignerExpectedServerCert =
      TlsCertificateDefinition.loadFromResource("tls/cert2.pfx", "password2");

  final HttpServer web3ProviderHttpServer =
      serverFactory.create(serverPresentedCert, ethSignerCert, workDir);

  signer =
      createAndStartSigner(
          ethSignerCert,
          ethSignerExpectedServerCert,
          web3ProviderHttpServer.actualPort(),
          0,
          workDir);

  assertThatThrownBy(() -> signer.accounts().balance("0x123456"))
      .isInstanceOf(ClientConnectionException.class)
      .hasMessageContaining(String.valueOf(BAD_GATEWAY.code()));

  // ensure submitting a transaction results in the same behaviour
  final Transaction transaction =
      Transaction.createEtherTransaction(
          signer.accounts().richBenefactor().address(),
          null,
          GAS_PRICE,
          INTRINSIC_GAS,
          "0x1b00ba00ca00bb00aa00bc00be00ac00ca00da00",
          Convert.toWei("1.75", Unit.ETHER).toBigIntegerExact());

  assertThatThrownBy(() -> signer.transactions().submit(transaction))
      .isInstanceOf(ClientConnectionException.class)
      .hasMessageContaining(String.valueOf(BAD_GATEWAY.code()));
}
 
Example #17
Source File: TransferEtherTest.java    From web3j_demo with Apache License 2.0 6 votes vote down vote up
/**
 * 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));
}
 
Example #18
Source File: DataPathFeatureFlagAcceptanceTest.java    From ethsigner with Apache License 2.0 6 votes vote down vote up
@Test
public void valueTransfer() {
  final BigInteger transferAmountWei = Convert.toWei("1.75", Unit.ETHER).toBigIntegerExact();
  final BigInteger startBalance = ethNode().accounts().balance(RECIPIENT);
  final Transaction transaction =
      Transaction.createEtherTransaction(
          richBenefactor().address(),
          null,
          GAS_PRICE,
          INTRINSIC_GAS,
          RECIPIENT,
          transferAmountWei);

  final String hash = ethSigner().transactions().submit(transaction);
  ethNode().transactions().awaitBlockContaining(hash);

  final BigInteger expectedEndBalance = startBalance.add(transferAmountWei);
  final BigInteger actualEndBalance = ethNode().accounts().balance(RECIPIENT);
  assertThat(actualEndBalance).isEqualTo(expectedEndBalance);
}
 
Example #19
Source File: TransferDemo.java    From web3j_demo with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #20
Source File: UniversalLinkTypeTest.java    From alpha-wallet-android with MIT License 6 votes vote down vote up
@Test
public void GenerateCurrencyLink() throws SalesOrderMalformed
{
    //generate link
    BigInteger szaboAmount = com.alphawallet.token.tools.Convert.fromWei(DROP_VALUE, com.alphawallet.token.tools.Convert.Unit.SZABO).abs().toBigInteger();
    expireTomorrow = System.currentTimeMillis() + 1000 * 60 * 60 * 24;
    expireTomorrow = expireTomorrow / 1000; //convert to seconds

    //This generates the 'message' part of the transaction
    //--- this is bitwise identical to message the 'formMessage' internal function in the Ethereum contract generates.
    byte[] tradeBytes = parser.getCurrencyBytes(CONTRACT_ADDR, szaboAmount, expireTomorrow, NONCE);

    //sign the tradeBytes with the testKey generated above
    byte[] signature = getSignature(tradeBytes);

    //add the currency link designation on the front
    byte[] linkMessage = ParseMagicLink.generateCurrencyLink(tradeBytes);

    //now complete the link by adding the signature on the end
    String universalLink = parser.completeUniversalLink(1,linkMessage, signature);

    System.out.println(universalLink);

    //now ensure we can extract all the information correctly
    CheckCurrencyLink(universalLink);
}
 
Example #21
Source File: ValueTransferWithHashicorpOnTlsAcceptanceTest.java    From ethsigner with Apache License 2.0 6 votes vote down vote up
@Test
public void valueTransfer() {
  final BigInteger transferAmountWei =
      Convert.toWei("1.75", Convert.Unit.ETHER).toBigIntegerExact();
  final BigInteger startBalance = ethNode().accounts().balance(RECIPIENT);
  final Transaction transaction =
      Transaction.createEtherTransaction(
          richBenefactor().address(),
          null,
          GAS_PRICE,
          INTRINSIC_GAS,
          RECIPIENT,
          transferAmountWei);

  final String hash = ethSigner().transactions().submit(transaction);
  ethNode().transactions().awaitBlockContaining(hash);

  final BigInteger expectedEndBalance = startBalance.add(transferAmountWei);
  final BigInteger actualEndBalance = ethNode().accounts().balance(RECIPIENT);
  assertThat(actualEndBalance).isEqualTo(expectedEndBalance);
}
 
Example #22
Source File: SendingCurrencyActivity.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
private void updateFee() {
    BigInteger defaultGasLimit = BigInteger.valueOf(DEFAULT_GAS_LIMIT);
    BigInteger fee = gasPrice.multiply(defaultGasLimit);
    currentFeeEth = Convert.fromWei(new BigDecimal(fee), Convert.Unit.ETHER);
    DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance();
    symbols.setDecimalSeparator('.');
    DecimalFormat decimalFormat = new DecimalFormat(ETH_SHOW_PATTERN_EXT, symbols);
    String feeStr = decimalFormat.format(currentFeeEth);
    etFeeAmount.setText(feeStr);
    updateArrivalField();
}
 
Example #23
Source File: SendingCurrencyActivity.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
private void updateGasLimitForFeeMode() {
    String newFeeStr = etFeeAmount.getText().toString();
    BigInteger currentFeeWei = Convert.toWei(newFeeStr, Convert.Unit.ETHER).toBigInteger();
    gasLimitForFeeMode = currentFeeWei.divide(gasPrice);
    btnConfirm.setEnabled(true);
    updateArrivalField();
}
 
Example #24
Source File: SignTransactionIT.java    From web3j with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #25
Source File: Transfer.java    From web3j with Apache License 2.0 5 votes vote down vote up
public static RemoteCall<TransactionReceipt> sendFunds(
        Web3j web3j,
        Credentials credentials,
        String toAddress,
        BigDecimal value,
        Convert.Unit unit)
        throws InterruptedException, IOException, TransactionException {

    TransactionManager transactionManager = new RawTransactionManager(web3j, credentials);

    return new RemoteCall<>(
            () -> new Transfer(web3j, transactionManager).send(toAddress, value, unit));
}
 
Example #26
Source File: SendingTokensActivity.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
private void updateFee() {

        BigInteger defaultGasLimit = BigInteger.valueOf(DEFAULT_GAS_LIMIT_FOR_CONTRACT);
        BigInteger fee = gasPrice.multiply(defaultGasLimit);
        currentFeeEth = Convert.fromWei(new BigDecimal(fee), Convert.Unit.ETHER);
        DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance();
        symbols.setDecimalSeparator('.');
        DecimalFormat decimalFormat = new DecimalFormat(ETH_SHOW_PATTERN, symbols);
        String feeStr = decimalFormat.format(currentFeeEth);
        etFeeAmount.setText(feeStr);
    }
 
Example #27
Source File: WalletSendFunds.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
private void confirmTransfer(
        BigDecimal amountToTransfer, Convert.Unit transferUnit, BigDecimal amountInWei,
        String destinationAddress) {

    console.printf("Please confim that you wish to transfer %s %s (%s %s) to address %s%n",
            amountToTransfer.stripTrailingZeros().toPlainString(), transferUnit,
            amountInWei.stripTrailingZeros().toPlainString(),
            Convert.Unit.WEI, destinationAddress);
    String confirm = console.readLine("Please type 'yes' to proceed: ").trim();
    if (!confirm.toLowerCase().equals("yes")) {
        exitError("OK, some other time perhaps...");
    }
}
 
Example #28
Source File: SignTransactionIT.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
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);
}
 
Example #29
Source File: WalletSendFunds.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
private Convert.Unit getTransferUnit() {
    String unit = console.readLine("Please specify the unit (ether, wei, ...) [ether]: ")
            .trim();

    Convert.Unit transferUnit;
    if (unit.equals("")) {
        transferUnit = Convert.Unit.ETHER;
    } else {
        transferUnit = Convert.Unit.fromString(unit.toLowerCase());
    }

    return transferUnit;
}
 
Example #30
Source File: Transfer.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
private TransactionReceipt send(
        String toAddress, BigDecimal value, Convert.Unit unit, BigInteger gasPrice,
        BigInteger gasLimit) throws IOException, InterruptedException,
        TransactionException {

    BigDecimal weiValue = Convert.toWei(value, unit);
    if (!Numeric.isIntegerValue(weiValue)) {
        throw new UnsupportedOperationException(
                "Non decimal Wei value provided: " + value + " " + unit.toString()
                        + " = " + weiValue + " Wei");
    }

    String resolvedAddress = ensResolver.resolve(toAddress);
    return send(resolvedAddress, "", weiValue.toBigIntegerExact(), gasPrice, gasLimit);
}