ETH 基础篇 JAVA Web3j 智能合约
架构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);后续的再补吧,今天到这里了
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: ThinkPHP5-简单的批量查询
- 下一篇: ETH 开发环境搭建及智能合约 helloworld