主页 > imtoken授权管理系统 > eth geth Android_Android与以太坊(ETH)智能合约交互
eth geth Android_Android与以太坊(ETH)智能合约交互
所谓与合约的交互,就是合约部署后,客户端连接到以太坊节点,然后调用合约方法。
部署智能合约的步骤
一般来说,部署智能合约的步骤是:
1.启动一个以太坊节点(比如geth或者testrpc)以太坊安卓下载,或者使用Infura直接连接。
2. 使用solc编译智能合约。 => 获取二进制代码。
3. 将编译好的合约部署到网络上。 (此步骤会消耗以太币,同时您还需要使用您节点的默认地址或指定地址来签署合约。) => 获取合约的区块链地址和ABI(合约接口的JSON表示,包括变量、事件和调用方法)。
4.使用web3j提供的API调用合约。 (某些调用类型会消耗以太币。)
对于步骤2和3,Remix可以直接完成。
案例分析
1.编写一个简单的合约文件SimpleStorage.sol
pragma solidity ^0.4.0;
合同简单存储{
uint 存储数据;
函数集(uint num){
存储数据 = num;
}
函数 get() 常量返回 (string retVal){
return "first depoly call contract";
}
}
2.通过solc和web3j命令行工具将sol合约文件编译成Java类SimpleStorage.class
3.测试节点是否连接成功
这里我连接到 infura 的 Rinkeby 测试网络
String rinkebyUrl = "https://rinkeby.infura.io/v3/YOURE-API-KEY";
Web3j web3j = Web3jFactory.build(new HttpService(rinkebyUrl));
/**
* 获取版本信息
*/
public void getWeb3ClientVersion() {
尝试 {
Web3ClientVersion web3ClientVersion = web3j。 web3ClientVersion()。 发送异步()。 得到();
Log.i(TAG, "getWeb3ClientVersion: " + web3ClientVersion.getWeb3ClientVersion());
} 赶上(InterruptedException e){
e.printStackTrace();
} 赶上(ExecutionException e){
e.printStackTrace();
}
}
如果能返回版本号,则连接成功。
4.部署合约
注意:可以使用remix+MetaMask或者Mist钱包部署合约,也可以使用代码部署
//加载账户信息,传输私钥
凭证凭证 = 凭证。 创建(私钥);
/**
* 部署合约
*/
公共无效部署(){
//部署智能合约
尝试 {
SimpleStorage simpleStorage = SimpleStorage.deploy(web3j, credentials, Contract.GAS_PRICE, Contract.GAS_LIMIT).sendAsync().get();
//部署合约后的地址
字符串 deployContractAddress = simpleStorage。 getContractAddress();
Log.i(TAG, "deployContractAddress : " + deployContractAddress);
加载(部署合约地址);
} 赶上(异常 e){
e.printStackTrace();
Log.i(TAG, "部署: " + e.getMessage());
}
}
SimpleStorage是编译SimpleStorage.sol合约文件生成的java类
5.加载合约
加载一个已经成功部署到ETH链上的合约
/**
* 加载已部署的合约
* @param contractAddress 合约地址
*/
public void load(String contractAddress) {
simpleStorage = SimpleStorage.load(contractAddress, web3j, credentials, Contract.GAS_PRICE, Contract.GAS_LIMIT);
新线程(新可运行(){
@覆盖
公共无效运行(){
尝试 {
布尔 isValid = simpleStorage。 已验证();
Log.i(TAG, "合同有效:" + isValid);
如果(有效){
得到();
}
} 赶上(IOException e){
e.printStackTrace();
Log.i(TAG, "load: " + e.getMessage());
}
}
})。开始();
}
simpleStorage.isValid() 是为了验证合约是否可用。 如果合约地址没有问题以太坊安卓下载,那么就可以调用合约方法进行交互了。
6.合约交互
注意:这是在合约中调用 get() 方法
/**
* 调用合约的方法
*/
公共无效得到(){
RemoteCall remoteCall = simpleStorage. 得到();
尝试 {
字符串结果 = remoteCall。 发送异步()。 得到();
Log.i(TAG, "得到结果:" + result);
} 赶上(InterruptedException e){
e.printStackTrace();
Log.i(TAG, "get: " + e.getMessage());
} 赶上(ExecutionException e){
e.printStackTrace();
Log.i(TAG, "get: " + e.getMessage());
}
}
get这里在java类中是这样的
公共 RemoteCall get() {
最终函数函数=新函数(FUNC_GET,
阵列。 作为列表(),
Arrays.>asList(new TypeReference() {}));
返回 executeRemoteCallSingleValueReturn(function, String.class);
}
调用合约get()方法的结果
至此,android与ETH合约交互成功。