若是要下載整個以太坊區塊鏈並保持本地節點同步。當區塊鏈佔用了我計算機上超過100GB的空間。這在臺式計算機上可能有意義,但在移動設備上則不太合理。java
解決此限制的一種方法是使用像Infura這樣的服務。Infura容許你鏈接到遠程以太坊節點並執行交易,而無需擔憂維護和同步本地節點。git
爲了可以使用本機Java代碼與智能合約進行交易,咱們使用一個名爲Web3j的庫。Web3j爲你提供生成智能合約java封裝包的實用程序,以及經過HTTP和IPC完整實現以太坊的JSON-RPC客戶端API。它提供了更多功能,但剛說的這些對這個「Android Ethereum hello world」示例來講最重要的功能。github
我想要與之互動的示例智能合約是一個Greeter。它在區塊鏈上存儲能夠讀取或更新的問候消息。它看起來像這樣:web
contract greeter is mortal { /* define variable greeting of the type string */ string greeting; /* this runs when the contract is executed */ function greeter(string _greeting) public { greeting = _greeting; } /* change greeting */ function changeGreeting(string _greeting) public { greeting = _greeting; } /* main function */ function greet() constant returns (string) { return greeting; } }
爲了可以建立封裝包,咱們首先要編譯這個智能合約:區塊鏈
solc greeter.sol --bin --abi --optimize -o <output-dir>/
要生成運行的封裝包:ui
web3j solidity generate /path/to/<smart-contract>.bin /path/to/<smart-contract>.abi -o /path/to/src/main/java -p com.your.organisation.name
首先,咱們須要得到以太坊區塊鏈交互的Web3實例。它看起來像這樣:this
InfuraHttpService infuraHttpService = new InfuraHttpService(url); Web3j web3j = Web3jFactory.build("https://ropsten.infura.io/YOUR_API_KEY");
如今咱們能夠讀取合約幾乎是即時的。url
Greeter greeter = Greeter.load(greeterContractAddress, web3j, credentials, gasPrice, gasLimit); Future<Utf8String> greeting = greeter.greet(); Utf8String greetingUtf8 = greeting.get(); String result = greetingUtf8.getValue();
但交易不是即時的,可能須要幾分鐘才能獲得驗證。code
Greeter greeter = Greeter.load(greeterContractAddress, web3j, credentials, gasPrice, gasLimit); TransactionReceipt transactionReceipt = greeter.changeGreeting(new Utf8String(greetingToWrite)).get(timeout); String result = "Successful transaction. Gas used: " + transactionReceipt.getGasUsed();
完整的例子看github這裏。ip