Java Code Examples for org.web3j.utils.Convert

The following examples show how to use org.web3j.utils.Convert. These examples are extracted from open source projects. 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 Project: ethsigner   Source File: ConnectionTimeoutAcceptanceTest.java    License: 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 2
Source Project: web3j_demo   Source File: TransferEtherTest.java    License: 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 3
@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 4
Source Project: web3j_demo   Source File: TransferDemo.java    License: 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 5
Source Project: alpha-wallet-android   Source File: UniversalLinkTypeTest.java    License: 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 6
@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 7
@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 8
@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 9
Source Project: besu   Source File: Amount.java    License: 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 Project: Android-Wallet-Token-ERC20   Source File: SendingEther.java    License: 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 11
Source Project: client-sdk-java   Source File: RestrictingScenario.java    License: 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 12
Source Project: client-sdk-java   Source File: WalletSendFunds.java    License: 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 13
Source Project: web3j   Source File: Transfer.java    License: 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 14
Source Project: alpha-wallet-android   Source File: ConfirmationActivity.java    License: 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 15
Source Project: client-sdk-java   Source File: PayWagesTest.java    License: 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 16
Source Project: client-sdk-java   Source File: PayWagesTest.java    License: 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 17
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 18
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 19
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 20
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 21
Source Project: jbpm-work-items   Source File: EthereumUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static TransactionReceipt sendFundsToContract(Credentials credentials,
                                                     Web3j web3j,
                                                     int etherAmount,
                                                     String toAddress,
                                                     Transfer transfer) throws Exception {

    return transfer.sendFunds(
            toAddress,
            new BigDecimal(etherAmount),
            Convert.Unit.ETHER).send();
}
 
Example 22
private void updateFee() {

        BigInteger defaultGasLimit = BigInteger.valueOf(DEFAULT_GAS_LIMIT);
        BigInteger fee = BigInteger.ZERO;
        if (gasPrice != null) {
            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);
        updateArrivalField();
    }
 
Example 23
Source Project: ethsigner   Source File: ClientSideTlsAcceptanceTest.java    License: Apache License 2.0 5 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 24
Source Project: web3j   Source File: Transfer.java    License: Apache License 2.0 5 votes vote down vote up
public RemoteCall<TransactionReceipt> sendFunds(
        String toAddress,
        BigDecimal value,
        Convert.Unit unit,
        BigInteger gasPrice,
        BigInteger gasLimit) {
    return new RemoteCall<>(() -> send(toAddress, value, unit, gasPrice, gasLimit));
}
 
Example 25
Source Project: besu   Source File: TransferTransaction.java    License: Apache License 2.0 5 votes vote down vote up
private BigInteger convertGasPriceToWei(final Amount unconverted) {
  final BigInteger price =
      Convert.toWei(unconverted.getValue(), unconverted.getUnit()).toBigInteger();

  if (MINIMUM_GAS_PRICE.compareTo(price) > 0) {
    throw new IllegalArgumentException(
        String.format(
            "Gas price: %s WEI, is below the accepted minimum: %s WEI",
            price, MINIMUM_GAS_PRICE));
  }

  return price;
}
 
Example 26
Source Project: ethereum-paper-wallet   Source File: Application.java    License: Apache License 2.0 5 votes vote down vote up
private String createOfflineTx() {
	readPassPhrase();
	
	try {
		PaperWallet pw = new PaperWallet(passPhrase, new File(walletFile));
		BigInteger gasPrice = PaperWallet.GAS_PRICE_DEFAULT;
		BigInteger gasLimit = PaperWallet.GAS_LIMIT_DEFAULT;
		BigInteger amountWei = Convert.toWei(String.valueOf(amount), Convert.Unit.ETHER).toBigInteger();

		log("Target address: " + targetAddress);
		log("Amount [Ether]: " + amount);
		log("Nonce: " + nonce);
		log("Gas price [Wei]: " + gasPrice);
		log("Gas limit [Wei]: " + gasLimit);
		
		String txData = pw.createOfflineTx(targetAddress, gasPrice, gasLimit, amountWei, BigInteger.valueOf(nonce));
		String curlCmd = String.format("curl -X POST --data '{\"jsonrpc\":\"2.0\",\"method\":\"eth_sendRawTransaction\",\"params\":[\"%s\"],\"id\":1}' -H \"Content-Type: application/json\" https://mainnet.infura.io/<infura-token>", txData);
		
		log(curlCmd);
		
		return curlCmd;
	} 
	catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
	return null;
}
 
Example 27
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 28
Source Project: BitcoinWallet   Source File: SendTransaction.java    License: MIT License 5 votes vote down vote up
public void sendTransaction(String fromAddress, String toAddress, BigDecimal amount, String password, WalletFile walletfile) throws Exception {
    BigInteger mNonce = getNonce(fromAddress);
    BigInteger gasPrice = getGasPrice();
    BigInteger value = Convert.toWei(amount, Convert.Unit.ETHER).toBigInteger();
    Transaction transaction = Transaction.createEtherTransaction(fromAddress, null,
            null, null, toAddress, value);
    BigInteger gasLimit = getGasLimit(transaction);
    String sign = new TransactionManager().signedEthTransactionData(toAddress, mNonce, gasPrice,
            gasLimit, amount, walletfile, password);
    sendTransaction(sign);

}
 
Example 29
Source Project: client-sdk-java   Source File: StakingScenario.java    License: Apache License 2.0 5 votes vote down vote up
public TransactionResponse addStaking() throws Exception {
    StakingAmountType stakingAmountType = StakingAmountType.FREE_AMOUNT_TYPE;
    BigDecimal addStakingAmount = Convert.toVon("4000000", Unit.LAT).add(new BigDecimal("999999999999999998"));

    PlatonSendTransaction platonSendTransaction = stakingContract.addStakingReturnTransaction(nodeId, stakingAmountType, addStakingAmount.toBigInteger()).send();
    TransactionResponse baseResponse = stakingContract.getTransactionResponse(platonSendTransaction).send();
    return baseResponse;
}
 
Example 30
Source Project: client-sdk-java   Source File: StakingScenario.java    License: Apache License 2.0 5 votes vote down vote up
public TransactionResponse staking() throws Exception {
    StakingAmountType stakingAmountType = StakingAmountType.FREE_AMOUNT_TYPE;
    String benifitAddress = benefitCredentials.getAddress();
    String externalId = "";
    String nodeName = "integration-node1";
    String webSite = "https://www.platon.network/#/";
    String details = "integration-node1-details";
    BigDecimal stakingAmount = Convert.toVon("5000000", Unit.LAT).add(BigDecimal.valueOf(1L));
    BigInteger rewardPer = BigInteger.valueOf(1000L);

    PlatonSendTransaction platonSendTransaction = stakingContract.stakingReturnTransaction(new StakingParam.Builder()
            .setNodeId(nodeId)
            .setAmount(stakingAmount.toBigInteger())
            .setStakingAmountType(stakingAmountType)
            .setBenifitAddress(benifitAddress)
            .setExternalId(externalId)
            .setNodeName(nodeName)
            .setWebSite(webSite)
            .setDetails(details)
            .setBlsPubKey(blsPubKey)
            .setProcessVersion(web3j.getProgramVersion().send().getAdminProgramVersion())
            .setBlsProof(web3j.getSchnorrNIZKProve().send().getAdminSchnorrNIZKProve())
            .setRewardPer(rewardPer)
            .build()).send();
    TransactionResponse baseResponse = stakingContract.getTransactionResponse(platonSendTransaction).send();
    return baseResponse;
}