java开发区块链二
- 使用如下命令开启geth
- 这种命令开启后,就可以使用web3j的java包进行调用了
$ geth --rpc --rpccorsdomain "*" --datadir "%cd%/mydata" --port 30303 --rpcapi "db,eth,net,web3,personal,web3" --networkid 1234 --rpcport 8545 console 2
- 解锁账户,这里解锁20分钟
personal.unlockAccount(eth.accounts[0],"password", 1000*60*20)
-
到这里我相信大家已经学会了部署智能合约,以及一些基本的geth命令操作
-
下面我们需要部署java环境
-
这里使用jdk8 + gradle
-
使用gradle引入web3j
compile 'org.web3j:core:3.2.0'
compile 'com.squareup.okhttp3:okhttp:3.9.1'
compile 'org.slf4j:slf4j-nop:1.7.25'
-
使用上一章的操作,将合约编译成的java版本的并放入项目中
-
获取合约地址
$ hello
{
abi: [{
constant: false,
inputs: [{...}],
name: "main",
outputs: [{...}],
payable: false,
stateMutability: "nonpayable",
type: "function"
}],
address: "0x3fe9d462f620d970317e8c001821c0d99492f59a",
transactionHash: "0x628d58730fe362a3e901e1dbe134b8d939117075c37e6a17b58eae0e0ba623ff",
allEvents: function(),
main: function()
}
- 合约调用
// 获取凭证
// 密码 钱包凭证
Credentials credentials = WalletUtils.loadCredentials("123456", "F:\\Geth\\mydata\\keystore\\UTC--2018-01-22T01-44-28.192158200Z--6dfea531562b1b0adfbeabf230cdb6a6d5d21b51");
Web3j web3 = Web3j.build(new HttpService()); // defaults to http://localhost:8545/
//传入合约地址,自行对照
Hello_sol_hello contract = Hello_sol_hello.load(
"0x3fe9d462f620d970317e8c001821c0d99492f59a", web3, credentials, GAS_PRICE, GAS_LIMIT);
RemoteCall<BigInteger> main = contract.main(new BigInteger("100"));
BigInteger maincall = main.send();
System.out.println("maincall = [" + maincall + "]");