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
|", 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());

你可能感兴趣的:(以太坊)