Android怎么和以太坊智能合约交互

we3j简介

we3j是提供了一个java访问以太坊网络的接口。借助we3j我们可以操作以太坊网络,包括创建账户、创建合约、执行合约、交易、查询余额、转账都可以。
项目地址https://github.com/web3j/web3j

TIM截图20180412113940.png

移动app怎么和以太坊区块链直接交互?

########################################################
#######android app怎么和以太坊区块链直接交互
########################################################
android<----->web3j<----->web3<---
-->JSON-RPC<-----> Ethereum blockchain<----->smart contrats


########################################################
#######ios app怎么和以太坊区块链直接交互
########################################################
ios<----->web3swift<----->web3<----->JSON-RPC<--
---> Ethereum blockchain<----->smart contrats

你需要知道这些

如何申请一个测试环境的以太坊账户、钱包怎么使用、怎么部署合约、Metamask的使用
https://duvalcc.github.io/2018/01/12/Rospten-%E4%BB%A5%E5%A4%AA%E5%9D%8A%E6%B5%8B%E8%AF%95%E7%BD%91%E7%BB%9C%E7%9A%84%E4%BD%BF%E7%94%A8/

怎么编译智能合约到java格式?
https://www.cnblogs.com/hongpxiaozhu/p/8581002.html

android怎么和智能合约交互
https://blog.jayway.com/2017/08/23/interacting-with-ethereum-smart-contracts-from-android/

android demo下载

https://github.com/linuxhsj/AndroidWeb3jEthereum

代码说明

privateKeyRopsten 是什么?这是钱包私钥!是的、我把自己测试环境的私钥告诉你们了。怎创建的?我安装了Metamask后创建一个账号然后导出私钥的。如果要换成自己的私钥的话,你可以去你的钱包复制出你的私钥就可以了。

greeterContractAddressRopsten 是什么?这个就是合约的以太坊地址。如果你要使用你的合约,你可以先通过https://remix.ethereum.org创建你的合约、然后部署到以太坊上。然后找到你合约地址替换就好。具体可以参考https://duvalcc.github.io/Rospten-%E4%BB%A5%E5%A4%AA%E5%9D%8A%E6%B5%8B%E8%AF%95%E7%BD%91%E7%BB%9C%E7%9A%84%E4%BD%BF%E7%94%A8/2018/01/12/

ropstenUrl又是什么?这个是在infura上申请的一个key。区块链需要节点来挖矿、来跑交易、来确认交易对不对,但是呢全节点需要下载很多区块数据,你要去下载也可以,你可以使用mist钱包或者以太坊钱包,但是需要下载很多数据,需要很久才可以下载完。infura提供一种服务、让你可以访问云端的节点、就是说我们不用下载所有的区块数据了,我们通过infura可以直接连接到全节点。我们只要关注于怎么和以太坊交互就好了。要换成你自己的key话你可以去这里https://infura.io/signup注册自己的账号。

package com.example.noev.greeter;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import org.web3j.abi.datatypes.Utf8String;
import org.web3j.crypto.Credentials;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.Web3jFactory;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.protocol.infura.InfuraHttpService;

import java.math.BigInteger;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * Main Ethereum Network
 * https://mainnet.infura.io/[your-token]
 * 

* Test Ethereum Network (Ropsten) * https://ropsten.infura.io/[your-token] *

* Test Rinkeby Network * https://rinkeby.infura.io/[your-token] *

* IPFS Gateway * https://ipfs.infura.io *

* IPFS RPC * https://ipfs.infura.io:5001 */ public class MainActivity extends AppCompatActivity { // private final static String privateKeyRopsten = "YOUR_PRIVATE_KEY"; private final static String privateKeyRopsten = "3d12dae3ebd0406deb87a5f1b937d96ae767648ad1252bec20745729a49e3db5"; //etherscan查看合约https://ropsten.etherscan.io/address/0x024b64940518779068e57352F3bDDdE08E4D9c40 private final static String greeterContractAddressRopsten = "0x024b64940518779068e57352F3bDDdE08E4D9c40"; // private final static String ropstenUrl = "https://ropsten.infura.io/YOUR_API_KEY"; private final static String ropstenUrl = "https://ropsten.infura.io/344WiX6NRUEc1PgSS93M"; private ProgressBar progressBar; private EditText editText; private TextView greetingTextView; private TextView gasPriceTextView; private TextView gasLimitTextView; private SeekBar gasPriceSeekBar; private Web3j web3j; private Credentials credentials = Credentials.create(privateKeyRopsten); private int minimumGasLimit = 21000; private BigInteger gasLimit = new BigInteger(String.valueOf(minimumGasLimit)); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initUi(); setGasPriceText(10); setGasLimit(minimumGasLimit); initWeb3j(); } private void initUi() { progressBar = (ProgressBar) findViewById(R.id.progressbar); editText = (EditText) findViewById(R.id.edit_text); greetingTextView = (TextView) findViewById(R.id.text); Button readButton = (Button) findViewById(R.id.button); readButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getGreeting(); } }); Button writeButton = (Button) findViewById(R.id.write_button); writeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { writeGreetingToContract(); } }); gasPriceSeekBar = (SeekBar) findViewById(R.id.gas_price_seek_bar); gasPriceSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { setGasPriceText(progress); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); SeekBar gasLimitSeekBar = (SeekBar) findViewById(R.id.gas_limit_seek_bar); gasLimitSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { setGasLimit(progress + minimumGasLimit); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); gasLimitTextView = (TextView) findViewById(R.id.gas_limit_text_view); gasPriceTextView = (TextView) findViewById(R.id.gas_price_text_view); } private void writeGreetingToContract() { progressBar.setVisibility(View.VISIBLE); WriteTask writeTask = new WriteTask(); writeTask.execute(editText.getText().toString()); } private void getGreeting() { try { progressBar.setVisibility(View.VISIBLE); ReadTask readTask = new ReadTask(); readTask.execute(); } catch (Exception e) { Log.d("wat", "getGreeting exception = " + e.getMessage()); } } private void initWeb3j() { InitWeb3JTask task = new InitWeb3JTask(); task.execute(ropstenUrl); } public void setGasPriceText(int gasPrice) { String formattedString = getString(R.string.gas_price, String.valueOf(gasPrice)); gasPriceTextView.setText(formattedString); } private BigInteger getGasPrice() { int gasPriceGwei = gasPriceSeekBar.getProgress(); BigInteger gasPriceWei = BigInteger.valueOf(gasPriceGwei + 1000000000L); Log.d("wat", "getGasPrice: " + String.valueOf(gasPriceGwei)); return gasPriceWei; } public void setGasLimit(int gasLimit) { String gl = String.valueOf(gasLimit); this.gasLimit = new BigInteger(gl); gasLimitTextView.setText(getString(R.string.gas_limit, gl)); } private class ReadTask extends AsyncTask { @Override protected String doInBackground(String... params) { String result; try { Greeter greeter = Greeter.load(greeterContractAddressRopsten, web3j, credentials, getGasPrice(), gasLimit); Future greeting = greeter.greet(); Utf8String greetingUtf8 = greeting.get(); result = greetingUtf8.getValue(); } catch (Exception e) { result = "Error reading the smart contract. Error: " + e.getMessage(); } return result; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); progressBar.setVisibility(View.INVISIBLE); greetingTextView.setText(result); } } private class WriteTask extends AsyncTask { @Override protected String doInBackground(String... params) { String greetingToWrite = params[0]; String result; try { Greeter greeter = Greeter.load(greeterContractAddressRopsten, web3j, credentials, getGasPrice(), gasLimit); TransactionReceipt transactionReceipt = greeter.changeGreeting(new Utf8String(greetingToWrite)).get(3, TimeUnit.MINUTES); result = "Successful transaction. Gas used: " + transactionReceipt.getGasUsed(); } catch (Exception e) { result = "Error during transaction. Error: " + e.getMessage(); } return result; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); progressBar.setVisibility(View.INVISIBLE); Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show(); } } private class InitWeb3JTask extends AsyncTask { @Override protected String doInBackground(String... params) { String url = params[0]; InfuraHttpService infuraHttpService; String result = "Success initializing web3j/infura"; try { infuraHttpService = new InfuraHttpService(url); web3j = Web3jFactory.build(infuraHttpService); } catch (Exception wtf) { String exception = wtf.toString(); Log.d("wat", "Error initializing web3j/infura. Error: " + exception); } return result; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show(); } } }

合约solidity源码greeter.sol

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;
    }
}

Greeter 是合约部分(这是由greeter.sol编译后生成的)
etherscan上查看这个合约https://ropsten.etherscan.io/address/0x024b64940518779068e57352F3bDDdE08E4D9c40


package com.example.noev.greeter;

import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.Future;
import org.web3j.abi.FunctionEncoder;
import org.web3j.abi.TypeReference;
import org.web3j.abi.datatypes.Function;
import org.web3j.abi.datatypes.Type;
import org.web3j.abi.datatypes.Utf8String;
import org.web3j.crypto.Credentials;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.tx.Contract;
import org.web3j.tx.TransactionManager;

/**
 * Auto generated code.
* Do not modify!
* Please use {@link org.web3j.codegen.SolidityFunctionWrapperGenerator} to update. * *

Generated with web3j version 2.2.1. */ public final class Greeter extends Contract { private static final String BINARY = "6060604052341561000c57fe5b604051610424380380610424833981016040528051015b5b60008054600160a060020a03191633600160a060020a03161790555b805161005390600190602084019061005b565b505b506100fb565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061009c57805160ff19168380011785556100c9565b828001600101855582156100c9579182015b828111156100c95782518255916020019190600101906100ae565b5b506100d69291506100da565b5090565b6100f891905b808211156100d657600081556001016100e0565b5090565b90565b61031a8061010a6000396000f300606060405263ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166341c0e1b58114610050578063cfae321714610062578063d28c25d4146100f2575bfe5b341561005857fe5b61006061014a565b005b341561006a57fe5b61007261018c565b6040805160208082528351818301528351919283929083019185019080838382156100b8575b8051825260208311156100b857601f199092019160209182019101610098565b505050905090810190601f1680156100e45780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34156100fa57fe5b610060600480803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284375094965061022495505050505050565b005b6000543373ffffffffffffffffffffffffffffffffffffffff908116911614156101895760005473ffffffffffffffffffffffffffffffffffffffff16ff5b5b565b61019461023c565b60018054604080516020600284861615610100026000190190941693909304601f810184900484028201840190925281815292918301828280156102195780601f106101ee57610100808354040283529160200191610219565b820191906000526020600020905b8154815290600101906020018083116101fc57829003601f168201915b505050505090505b90565b805161023790600190602084019061024e565b505b50565b60408051602081019091526000815290565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061028f57805160ff19168380011785556102bc565b828001600101855582156102bc579182015b828111156102bc5782518255916020019190600101906102a1565b5b506102c99291506102cd565b5090565b61022191905b808211156102c957600081556001016102d3565b5090565b905600a165627a7a72305820d149a1ef7f946206a37416ac53bfb06d18b4f2768c9fab7facfa51344ab911cd0029"; private Greeter(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); } private Greeter(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); } public Future kill() { Function function = new Function("kill", Arrays.asList(), Collections.>emptyList()); return executeTransactionAsync(function); } public Future greet() { Function function = new Function("greet", Arrays.asList(), Arrays.>asList(new TypeReference() {})); return executeCallSingleValueReturnAsync(function); } public Future changeGreeting(Utf8String _greeting) { Function function = new Function("changeGreeting", Arrays.asList(_greeting), Collections.>emptyList()); return executeTransactionAsync(function); } public static Future deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit, BigInteger initialWeiValue, Utf8String _greeting) { String encodedConstructor = FunctionEncoder.encodeConstructor(Arrays.asList(_greeting)); return deployAsync(Greeter.class, web3j, credentials, gasPrice, gasLimit, BINARY, encodedConstructor, initialWeiValue); } public static Future deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit, BigInteger initialWeiValue, Utf8String _greeting) { String encodedConstructor = FunctionEncoder.encodeConstructor(Arrays.asList(_greeting)); return deployAsync(Greeter.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, encodedConstructor, initialWeiValue); } public static Greeter load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { return new Greeter(contractAddress, web3j, credentials, gasPrice, gasLimit); } public static Greeter load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { return new Greeter(contractAddress, web3j, transactionManager, gasPrice, gasLimit); } }

依赖部分


dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    compile fileTree(dir: 'libs', include: ['*.jar'])
//    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
//        exclude group: 'com.android.support', module: 'support-annotations'
//    })
    compile 'com.android.support:appcompat-v7:26.0.0'
//    compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha8'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'org.web3j:core-android:2.2.1'
//    testCompile 'junit:junit:4.12'
}

运行说明

当你把程序放到android studio跑起来的时候、手机上可以看到get greeting和write按钮。
1、点击get greeting默认会返回hey man.
2、再输入框中你可以输入你需要修改的值,比如我输入how are you,然后点击write就是要提交以太坊上去,执行合约需要消耗eter。你需要去申请,方法参考这个https://duvalcc.github.io/Rospten-%E4%BB%A5%E5%A4%AA%E5%9D%8A%E6%B5%8B%E8%AF%95%E7%BD%91%E7%BB%9C%E7%9A%84%E4%BD%BF%E7%94%A8/2018/01/12/
3、再次点击get greeting默认会返回how are you.

你可能感兴趣的:(Android怎么和以太坊智能合约交互)