架構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); 後續的再補吧,今天到這裡了