web3j入门

首先将最新版本的web3j安装到项目中。

<dependency>
  <groupId>org.web3j</groupId>
  <artifactId>core</artifactId>
  <version>3.4.0</version>
</dependency>

启动客户端 

使用客户端提供的免费的云端服务,这么启动:

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

 当不需要Web3j实例时,需要调用shutdown方法来释放它所使用的资源。

web3.shutdown()

新建和部署智能合约:

Web3j web3 = Web3j.build(new HttpService());  // 默认为http://localhost:8545/
Credentials credentials = WalletUtils.loadCredentials("password", "/path/to/walletfile");

YourSmartContract contract = YourSmartContract.deploy(
        <web3j>, <credentials>,
        GAS_PRICE, GAS_LIMIT,
        <param1>, ..., <paramN>).send(); 

或者使用一个现有的智能合约:

YourSmartContract contract = YourSmartContract.load(
        "0x<address>|<ensName>", <web3j>, <credentials>, GAS_PRICE, GAS_LIMIT);

然后就可以进行智能合约的交互了:

TransactionReceipt transactionReceipt = contract.someMethod(
             <param1>,
             ...).send();

调用智能合约:

Type result = contract.someMethod(<param1>, ...).send();

更多推荐