1. 程式人生 > >java基於web3j 玩轉eth

java基於web3j 玩轉eth

1.查詢ETH錢包餘額: private static final String URL = “http://127.0.0.1:8545/”; Web3j web3 = Web3j.build(new HttpService(URL)); EthGetBalance ethGetBalance = null; try { // 通過賬戶地址查詢餘額 ethGetBalance = web3j .ethGetBalance(“0xac***f0261bc4b0*0d5e23d9f80d24bf89fe”, DefaultBlockParameterName.LATEST) .sendAsync() .get(); } catch (Exception e) { throw new Exception(“查詢錢包餘額失敗”); } 1eth = 10e18 wei 單位轉換: BigDecimal banlance = Convert.fromWei(ethGetBalance.getBalance().toString(), Convert.Unit.ETHER);

  1. 通過錢包密碼和助記詞找回私鑰公鑰 通過密碼與助記詞獲得錢包地址、公鑰及私鑰資訊 Credentials credentials = WalletUtils.loadBip39Credentials(walletPwd, memorizingWords); //公鑰16進位制字串表示 String publicKey = credentials.getEcKeyPair().getPublicKey().toString(16); //私鑰16進位制字串表示 String privateKey = credentials.getEcKeyPair().getPrivateKey().toString(16);

3.獲得當前區塊高度 Web3j web3j = EthUtil.getConnection(); Request<?, EthBlockNumber> request = web3j.ethBlockNumber();

4.解鎖賬戶,傳送交易前需要對賬戶進行解鎖 /** * 通過http連線到geth節點 * * @return */ private static HttpService getService() { return new HttpService(URL); } public static Admin initAdmin() { return Admin.build(getService()); } Admin admin = EthUtil.initAdmin(); Request<?, PersonalUnlockAccount> request = admin.personalUnlockAccount(address, password, duration); PersonalUnlockAccount account = request.send();

5.查詢區塊內容 Web3j web3j = EthUtil.getConnection(); DefaultBlockParameter defaultBlockParameter = new DefaultBlockParameterNumber(blockNumber); Request<?, EthBlock> request = web3j.ethGetBlockByNumber(defaultBlockParameter, true); EthBlock ethBlock = request.send();