如何用web3j调用智能合约
2018-03-05 15:36
417 查看
在用web3j调用合约的时候会出现各种莫名其妙的bug,主要的原因有以下几点:
1.区块没同步完成:区块在同步完成之前即在服务器调用eth.syncing返回false之前操作账户一般都会有问题
2.gas price太低或者gas limit 异常都是因为调用的方法不对
3.连接超时是因为得设置httpclient的超时时间
4.调用之前需要将合约代码编译成.java格式的文件,具体编译方法参照web3j.io
废话不多说直接贴代码:
package com.springboot.controller;
import okhttp3.OkHttpClient;
import org.apache.commons.io.FileUtils;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.WalletUtils;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.protocol.http.HttpService;
import java.io.File;
import java.io.InputStream;
import java.math.BigInteger;
import java.util.concurrent.TimeUnit;
import static org.web3j.tx.Contract.GAS_LIMIT;
@Controller
@EnableAutoConfiguration
public class SampleController {
@RequestMapping(value = "/index", method = RequestMethod.GET)
@ResponseBody
String home(@RequestParam("to") String a, @RequestParam("numbers") String b) {// to 收币地址 numbers 转币数量
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
HttpService httpService = new HttpService(HttpService.DEFAULT_URL, client, false);
Web3j web3j = Web3j.build(httpService);
String bb = "";
Credentials credentials = null;
try {
InputStream stream = getClass().getClassLoader().getResourceAsStream("钱包地址一般放在resource下面");
File targetFile = new File("钱包地址");
FileUtils.copyInputStreamToFile(stream, targetFile);
credentials = WalletUtils.loadCredentials("钱包密码", targetFile);
System.out.println("credentials=" + credentials.getAddress());
Lap contract = Lap.load("合约地址", web3j, credentials,
web3j.ethGasPrice().send().getGasPrice(), GAS_LIMIT);
TransactionReceipt balanceOf = contract.transfer(a, aDouble(b)).sendAsync().get();
System.out.println("hashId=" + balanceOf.getTransactionHash());
return msg("1","success",balanceOf.getTransactionHash());
} catch (Exception e) {
bb = e.toString();
}
return msg("0",bb,"null");
}
public BigInteger aDouble(String s){
double m = Double.valueOf(s);
double mm = m*10000000000000000L;//根据合约的decimals转成需要的数量
BigInteger f = BigInteger.valueOf( Math.round(mm));
return f;
}
public String msg(String state,String msg,String id){
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("state", state);
jsonObject.put("msg", msg);
jsonObject.put("transationId", id);
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject.toString();
}
}
1.区块没同步完成:区块在同步完成之前即在服务器调用eth.syncing返回false之前操作账户一般都会有问题
2.gas price太低或者gas limit 异常都是因为调用的方法不对
3.连接超时是因为得设置httpclient的超时时间
4.调用之前需要将合约代码编译成.java格式的文件,具体编译方法参照web3j.io
废话不多说直接贴代码:
package com.springboot.controller;
import okhttp3.OkHttpClient;
import org.apache.commons.io.FileUtils;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.WalletUtils;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.protocol.http.HttpService;
import java.io.File;
import java.io.InputStream;
import java.math.BigInteger;
import java.util.concurrent.TimeUnit;
import static org.web3j.tx.Contract.GAS_LIMIT;
@Controller
@EnableAutoConfiguration
public class SampleController {
@RequestMapping(value = "/index", method = RequestMethod.GET)
@ResponseBody
String home(@RequestParam("to") String a, @RequestParam("numbers") String b) {// to 收币地址 numbers 转币数量
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
HttpService httpService = new HttpService(HttpService.DEFAULT_URL, client, false);
Web3j web3j = Web3j.build(httpService);
String bb = "";
Credentials credentials = null;
try {
InputStream stream = getClass().getClassLoader().getResourceAsStream("钱包地址一般放在resource下面");
File targetFile = new File("钱包地址");
FileUtils.copyInputStreamToFile(stream, targetFile);
credentials = WalletUtils.loadCredentials("钱包密码", targetFile);
System.out.println("credentials=" + credentials.getAddress());
Lap contract = Lap.load("合约地址", web3j, credentials,
web3j.ethGasPrice().send().getGasPrice(), GAS_LIMIT);
TransactionReceipt balanceOf = contract.transfer(a, aDouble(b)).sendAsync().get();
System.out.println("hashId=" + balanceOf.getTransactionHash());
return msg("1","success",balanceOf.getTransactionHash());
} catch (Exception e) {
bb = e.toString();
}
return msg("0",bb,"null");
}
public BigInteger aDouble(String s){
double m = Double.valueOf(s);
double mm = m*10000000000000000L;//根据合约的decimals转成需要的数量
BigInteger f = BigInteger.valueOf( Math.round(mm));
return f;
}
public String msg(String state,String msg,String id){
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("state", state);
jsonObject.put("msg", msg);
jsonObject.put("transationId", id);
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject.toString();
}
}
相关文章推荐
- 如何开发编译部署调用智能合约
- 手把手教你搭建智能合约测试环境、开发、编译、部署以及如何通过JS调用合约方法
- 如何部署并调用ethereum智能合约
- 如何编写智能合约(Smart Contract)?(II)建立加密代币
- 使用web3j将sol智能合约转换成java文件
- 用web3j实现与智能合约交互
- 如何在微信公众号调用图灵机器人(智能聊天)
- 【区块链】以太坊 web3j for java 使用 - 部署和调用合约 <3>
- 如何使用数字货币开发工具来做智能合约的测试驱动开发
- 【附代码】如何在私有链上编写、部署与以太坊进行交互的智能合约
- 如何使用web3.js 部署智能合约
- 如何在Spring Boot中玩转智能合约
- C#如何进行以太坊合约调用交易,时间处理,使用过滤器和主题。
- 智能“排雷”技术,如何保障双11数据链路百亿次调用稳如泰山?
- 如何通过以太坊智能合约来进行众筹(ICO)
- 在geth客户端调用已部署的智能合约
- 如何编写一个可升级的智能合约
- 如何在私有区块链上编写、部署以及与以太坊进行交互的智能合约
- 以太坊智能合约代币应用开发(5)-web3调用智能代币合约
- 基于mcat开发智能合约应用(二)调用合约