架构springboot
这里使用web3j当前eth官方推荐的集成jdk来做说明!当然你也可以使用它最底层的rpc方案来编写(官网也有说明)!
这里做个总结
第一步:先引入jdk [maven]
- <dependency>
- <groupId>org.web3j</groupId>
- <artifactId>core</artifactId>
- <version>3.2.0</version>
- </dependency>
- Web3j web3 = Web3j.build(new HttpService("http://localhost:5201314/"));
- Web3ClientVersion web3ClientVersion;
- try {
- web3ClientVersion = web3.web3ClientVersion().send();
- String clientVersion = web3ClientVersion.getWeb3ClientVersion();
- System.out.println(clientVersion);
- } catch (IOException e) {
- e.printStackTrace();
- }
- String filePath = "E:/pictures";
- String fileName;
- // 创建钱包地址
- //eth-密码需要自己管理,自己设置哦!
- fileName = WalletUtils.generateNewWalletFile("设置你的密码", new File(filePath), false);
- System.out.println(fileName);//保存你的加密文件信息
- System.out.println(ALICE.getAddress());//钱包地址
- System.out.println(ALICE.getEcKeyPair().getPrivateKey());//私钥
- System.out.println(ALICE.getEcKeyPair().getPublicKey());//公钥
现在当然是最重要的是交易啦。
产生交易需要加载私钥和钱包地址。这里用引用文件的方式来加载钱包地址!
- String path='钱包加密文件地址';
- Credentials ALICE = WalletUtils.loadCredentials("你的密码", path);
- BigInteger nonce = getNonce("发送钱包地址");
- private static BigInteger getNonce(String address) throws Exception {
- EthGetTransactionCount ethGetTransactionCount =
- web3.ethGetTransactionCount(address,DefaultBlockParameterName.LATEST).sendAsync().get();
- return ethGetTransactionCount.getTransactionCount();
- }
- //发送金额
- RawTransaction rawTransaction = createEtherTransaction(nonce, "mubia钱包地址");
- private static RawTransaction createEtherTransaction(BigInteger nonce, String toAddress) {
- BigInteger value = Convert.toWei("数量", Convert.Unit.ETHER).toBigInteger();
- //交易手续费由price*limit来决定,所有这两个值你可以自定义,也可以使用系统参数获取当前两个值
影响的结果就是自定义手续费会影响到账时间,手续费过低矿机会最后才处理你的!使用系统的话,手续费可能会很高,系统
是获取当前最新成交的一笔手续来计算的。可能一笔需要几百人民币
return RawTransaction.createEtherTransaction(nonce, price,limit , toAddress, value);}
- //返回对象
- byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, ALICE);
- //交易订单号
- String hexValue = Numeric.toHexString(signedMessage);
- // //获取余额
- EthGetBalance ethGetBalance1 = web3.ethGetBalance("0xb86d57174bf8c53f1084be7f565f9fd9dabd87d0", DefaultBlockParameter.valueOf("latest")).send();
- //eth默认会部18个0这里处理比较随意,大家可以随便处理哈
- BigDecimal balance = new BigDecimal(ethGetBalance1.getBalance().divide(new BigInteger("10000000000000")).toString());
- BigDecimal nbalance = balance.divide(new BigDecimal("100000"), 8, BigDecimal.ROUND_DOWN);
- System.out.println(nbalance);