JAVA以太坊转账

1.ETH账户之间的转账

public class EthUtil {
private static final String URL = “http://127.0.0.1:8545/;
public static final String KEYSTOREPATH = “C:\Users\Administrator\AppData\Roaming\Ethereum\keystore”;
public static final String PASSWORD = “syy123456”;

/**

create eth wallet

@throws CipherException

@throws IOException
*/
public static String CreateWallet() throws CipherException, IOException {

Bip39Wallet wallet = WalletUtils.generateBip39Wallet(PASSWORD, new File(KEYSTOREPATH));

String fileName = wallet.getFilename();
return getAddress(fileName);
}

public static String getAddress(String fileName) {
String walletAddress = "0x" + fileName.substring(
         fileName.lastIndexOf("-") + 1,
         fileName.lastIndexOf("-") + 41);
 return walletAddress;
}

public static List IterateAllWallet(String path) {

 List<File> fileList = new ArrayList<File>();
 File file = new File(path);
 File[] files = file.listFiles();
 if (files == null) {
     return fileList;
 }
 for (File f : files) {
     if (f.isFile()) {
         fileList.add(f);
     } else if (f.isDirectory()) {
         System.out.println(f.getAbsolutePath());
         IterateAllWallet(f.getAbsolutePath());
     }
 }

// for (File f:fileList){
// System.out.println(getAddress(f.getName()));
// }
return fileList;
}

public static File getFileFromAddress(String address) {

    File file = new File(KEYSTOREPATH);
    if (!file.isDirectory() || file.listFiles().length == 0) {
        return null;
    }

    for (File f : file.listFiles()) {
        String fileName = f.getName();
        String walletAddress = "0x" + fileName.substring(fileName.lastIndexOf("-") + 1,
                fileName.lastIndexOf("-") + 41);
        if (address.equalsIgnoreCase(walletAddress)) {
            return f;
        }
    }
    return null;
}


/**
 * 连接eth
 *
 * @return
 */
public static Web3j getConnection() {
    Web3j web3 = Web3j.build(new HttpService(URL));
    return web3;
}

/**
 * 初始化admin级别操作的对象
 *
 * @return Admin
 */
public static Admin initAdmin() {
    return Admin.build(getService());
}

/**
 * 通过http连接到geth节点
 *
 * @return
 */
private static HttpService getService() {
    return new HttpService(URL);
}

}

Web3j web3j = EthUtil.getConnection();
String txHash = ethService.tranferEth(web3j, fromAddr, toAddr, amount, gasPrice, gasLimit, walletPwd);
if (StringUtils.isEmpty(txHash)) {
throw new Exception(“转账失败”);
}
@Transactional(rollbackFor = Exception.class)
@Override
public String tranferEth(Web3j web3j, String from, String to, String amount, String gasPrice1, String gasLimit1, String walletPwd) throws Exception {
//查询交易费
BigInteger gasPrice = new BigInteger(gasPrice1);
BigInteger gasLimit = new BigInteger(gasLimit1);
BigInteger gas = gasPrice.multiply(gasLimit);
BigInteger value = new BigInteger(amount);
BigInteger allFee = value.add(gas);
String transactionHash;
//获取指定钱包的以太币余额
try {
BigInteger balance = web3j.ethGetBalance(from, DefaultBlockParameterName.LATEST).send().getBalance();
if (balance.compareTo(allFee) < 0) {
throw new Exception(“账户余额不足”);
}
//交易凭证
Credentials credentials = WalletUtils.loadCredentials(walletPwd, EthUtil.getFileFromAddress(from));
EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(
from, DefaultBlockParameterName.LATEST).sendAsync().get();
BigInteger nonce = ethGetTransactionCount.getTransactionCount();
//普通交易
RawTransaction rawTransaction = RawTransaction.createEtherTransaction(
nonce, gasPrice, gasLimit, to, value);

        byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
        String hexValue = Numeric.toHexString(signedMessage);
        //发送交易
        EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).sendAsync().get();
        //交易的HASH
        transactionHash = ethSendTransaction.getTransactionHash();
    } catch (Exception e) {
        throw new Exception("转账失败!");
    }
    return transactionHash;
}

2.指定地址转ETH至合约地址

Result result = new Result();
Web3j web3j = EthUtil.getConnection();
String txHash = ethService.tranferToContractAddr(web3j, account, contractAddr, amount, gasPrice, gasLimit, walletPwd);
if (StringUtils.isEmpty(txHash)) {
throw new Exception(“转账失败”);
}
@Transactional(rollbackFor = Exception.class)
@Override
public String tranferToContractAddr(Web3j web3j, String from, String to, String value, String gasPrice, String gasLimit, String walletPwd) throws Exception {

    BigInteger balance = web3j.ethGetBalance(from, DefaultBlockParameterName.LATEST).send().getBalance();

    BigInteger gasPrice1 = new BigInteger(gasPrice);
    BigInteger gasLimit1 = new BigInteger(gasLimit);
    BigInteger gas = gasPrice1.multiply(gasLimit1);
// double temp = Math.pow(10, TokenOperate.DECIMAL);
BigInteger amount = new BigInteger(value);
BigInteger allFee = amount.add(gas);
//获取账户余额
// System.out.println(from + " balance :" + balance);
if (balance.compareTo(allFee) < 0) {
throw new Exception(“账户余额不足”);
}
//交易凭证
Credentials credentials = WalletUtils.loadCredentials(walletPwd, EthUtil.getFileFromAddress(from));
EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(
from, DefaultBlockParameterName.LATEST).sendAsync().get();
BigInteger nonce = ethGetTransactionCount.getTransactionCount();
//创建交易  注意金额 保留小数点后8位 要转化为整数 比如0.00000001 转化为1
    Function function = new Function(
            "_transfer",//交易的方法名称
            Arrays.asList(new Address(from), new Uint256(amount)),
            Arrays.asList(new TypeReference<Address>() {
            }, new TypeReference<Uint256>() {
            })
    );
    String encodedFunction = FunctionEncoder.encode(function);

    //智能合约交易
    RawTransaction rawTransaction = RawTransaction.createTransaction(nonce, gasPrice1, gasLimit1, to, encodedFunction);

    byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
    String hexValue = Numeric.toHexString(signedMessage);
    //发送交易
    EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).sendAsync().get();
    //交易的HASH
    String transactionHash = ethSendTransaction.getTransactionHash();
    return transactionHash;

}

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

云上上云

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值