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]
 * <p>
 * Test Ethereum Network (Ropsten)
 * https://ropsten.infura.io/[your-token]
 * <p>
 * Test Rinkeby Network
 * https://rinkeby.infura.io/[your-token]
 * <p>
 * IPFS Gateway
 * https://ipfs.infura.io
 * <p>
 * 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<String, String, String> {
        @Override
        protected String doInBackground(String... params) {
            String result;
            try {
                Greeter greeter = Greeter.load(greeterContractAddressRopsten, web3j, credentials, getGasPrice(), gasLimit);
                Future<Utf8String> 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<String, String, String> {
        @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<String, String, String> {
        @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.<br>
 * <strong>Do not modify!</strong><br>
 * Please use {@link org.web3j.codegen.SolidityFunctionWrapperGenerator} to update.
 *
 * <p>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<TransactionReceipt> kill() {
        Function function = new Function("kill", Arrays.<Type>asList(), Collections.<TypeReference<?>>emptyList());
        return executeTransactionAsync(function);
    }

    public Future<Utf8String> greet() {
        Function function = new Function("greet", 
                Arrays.<Type>asList(), 
                Arrays.<TypeReference<?>>asList(new TypeReference<Utf8String>() {}));
        return executeCallSingleValueReturnAsync(function);
    }

    public Future<TransactionReceipt> changeGreeting(Utf8String _greeting) {
        Function function = new Function("changeGreeting", Arrays.<Type>asList(_greeting), Collections.<TypeReference<?>>emptyList());
        return executeTransactionAsync(function);
    }

    public static Future<Greeter> deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit, BigInteger initialWeiValue, Utf8String _greeting) {
        String encodedConstructor = FunctionEncoder.encodeConstructor(Arrays.<Type>asList(_greeting));
        return deployAsync(Greeter.class, web3j, credentials, gasPrice, gasLimit, BINARY, encodedConstructor, initialWeiValue);
    }

    public static Future<Greeter> deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit, BigInteger initialWeiValue, Utf8String _greeting) {
        String encodedConstructor = FunctionEncoder.encodeConstructor(Arrays.<Type>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.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,172评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,346评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,788评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,299评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,409评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,467评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,476评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,262评论 0 269
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,699评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,994评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,167评论 1 343
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,827评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,499评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,149评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,387评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,028评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,055评论 2 352

推荐阅读更多精彩内容

  • 【Aipm引导页】 https://58976235.wodemo.net/down/20170514/44034...
    Mr_洛寒阅读 2,567评论 3 5
  • ## 2015.06.05 - [开源利弊浅谈 - 张超耀](移动组周技术分享总结#开源利弊浅谈---张超耀) -...
    XcodeYang阅读 1,490评论 1 3
  • 以太坊是什么玩意呢?为什么说以太坊开启了加密货币的2.0时代呢?它是凭借着什么而稳坐着加密货币的流通市值的第二把交...
    杰Sir有话说阅读 1,544评论 0 4
  • 有一些物料需要先设计好,然后去制作,例如灯布、展架、易拉宝等等这些。其实,这里涉及到两个环节,设计和制作,去找广告...
    宁小南阅读 353评论 0 0
  • 我是你蒋叔阅读 183评论 0 0