eth 创建钱包,转账 web3j
pom文件引入web3j 包
<dependency> <groupId>com.madgag.spongycastle</groupId> <artifactId>core</artifactId> <version>1.58.0.0</version> </dependency> <dependency> <groupId>org.web3j</groupId> <artifactId>utils</artifactId> <version>3.4.0</version> </dependency> <dependency> <groupId>org.web3j</groupId> <artifactId>core</artifactId> <version>>3.4.0</version> </dependency>
eth 创建钱包
public static void create() throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException, CipherException { ECKeyPair ecKeyPair = Keys.createEcKeyPair(); WalletFile walletFile = Wallet.createLight("password", ecKeyPair); String address = "0x" + walletFile.getAddress(); String privateKey = ecKeyPair.getPrivateKey().toString(16); String encryptPrivateKey = AesCBC.getInstance().simpleEncrypt(privateKey, AesCBC.makeKey(1 + "_" + 1)); System.out.println("address:"+ address); System.out.println("encryptPrivateKey:"+ encryptPrivateKey); }
eth 转账
public static void trans() throws ExecutionException, InterruptedException, IOException, CipherException{ //设置需要的矿工费 //调用的是kovan测试环境,这里使用的是infura这个客户端 Web3j web3j = Web3j.build(new HttpService("节点地址")); //转账人账户地址 String ownAddress = "转账地址"; //被转人账户地址 String toAddress = "收款地址"; //金额 String amount = "转账金额"; //转账人私钥 //Credentials credentials = Credentials.create("私钥"); Credentials credentials = WalletUtils.loadCredentials( "私钥", "keystore.store文件地址"); //getNonce(每成功交易一笔Nonce会增加) EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount( ownAddress, DefaultBlockParameterName.LATEST).sendAsync().get(); BigInteger nonce = ethGetTransactionCount.getTransactionCount(); //创建交易,这里是把金额转成wei的计价单位 BigInteger value = Convert.toWei(amount, Convert.Unit.ETHER).toBigInteger(); //获取手续费 EthGasPrice gasPrice = web3j.ethGasPrice().send(); //转账ETH RawTransaction rawTransaction = RawTransaction.createEtherTransaction( nonce, gasPrice.getGasPrice(), GAS_LIMIT, toAddress, value); // //转账代币 // Function function = new Function( // "transfer", // Arrays.asList(new Address(toAddress), new Uint256(value)), // Collections.emptyList()); // String data = FunctionEncoder.encode(function); // RawTransaction rawTransaction = RawTransaction.createTransaction( // nonce, // TransactionConstants.getUseGasPrice(gasPrice.getGasPrice()), // TransactionConstants.GAS_AMOUNT, // "代币地址", // data // ); //签名Transaction,这里要对交易做签名 byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials); String hexValue = Numeric.toHexString(signedMessage); //发送交易 EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).sendAsync().get(); String transactionHash = ethSendTransaction.getTransactionHash(); //获得到transactionHash后就可以到以太坊的网站上查询这笔交易的状态了 System.out.println(transactionHash); } /** * 对数字乘以10的18次方 * * @param amount 乘数 */ public static BigInteger toWei(String amount) { return new BigDecimal(amount).multiply(new BigDecimal(Math.pow(10, 18))).toBigInteger(); }
上一篇:
JS实现多线程数据分片下载