如何用web3j调用智能合约

在用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();
    }
 
}

你可能感兴趣的:(如何用web3j调用智能合约)