web3J入門操作

Web3j 入門操作

1.連接,選擇網絡

Web3j web3 = Web3j.build(new HttpService(“https://morden.infura.io/your-token”));

Web3j web3 = Web3j.build(new HttpService());  // defaults to http://localhost:8545/
Web3ClientVersion web3ClientVersion = web3.web3ClientVersion().send();
String clientVersion = web3ClientVersion.getWeb3ClientVersion();

2.轉賬:(需要授權)

Credentials credentials = WalletUtils.loadCredentials("password", "/path/to/walletfile");
TransactionReceipt transactionReceipt = Transfer.sendFunds(
        web3, credentials, "0x<address>|<ensName>",
        BigDecimal.valueOf(1.0), Convert.Unit.ETHER)
        .send();

3.通過助記符和密碼創建以太坊賬戶
Credentials credentials1 = WalletUtils.loadBip39Credentials(“密碼”, “十二位助記符”);
//公鑰16進制字符串表示
String publicKey = credentials1.getEcKeyPair().getPublicKey().toString(16);
//私鑰16進制字符串表示
System.out.println(“公鑰==》”+publicKey);
String privateKey = credentials1.getEcKeyPair().getPrivateKey().toString(16);
System.out.println(“私鑰==》”+privateKey);

4.解鎖賬戶
Admin web3j = Admin.build(new HttpService()); // defaults to http://localhost:8545/

	PersonalUnlockAccount personalUnlockAccount = web3j
			.personalUnlockAccount("賬戶", "密碼").sendAsync().get();
	System.out.println("賬戶解鎖==>" + personalUnlockAccount.accountUnlocked());

5:查詢區塊高度:

Request<?, EthBlockNumber> request1 = web3.ethBlockNumber();
		EthBlockNumber xia = request1.send();
		BigInteger xia2 = xia.getBlockNumber();
		System.out.println("區塊高度" + xia2);

6:通過區塊號查詢區塊信息:

DefaultBlockParameter defaultBlockParameter = new DefaultBlockParameterNumber(區塊號);
		Request<?, EthBlock> request = web3.ethGetBlockByNumber(defaultBlockParameter, true);
		EthBlock ethBlock = request.send();
		System.out.println("Hash==>" + ethBlock.getBlock().getHash());

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章