使用 java调用以太坊私链上的合约方法
引入java依赖 pom
<!--web3j-->
<dependency>
<groupId>org.web3j</groupId>
<artifactId>core</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>org.web3j</groupId>
<artifactId>geth</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>org.web3j</groupId>
<artifactId>abi</artifactId>
<version>3.4.0</version>
</dependency>
配置文件 application.yml
contract:
ctAddr: "************************************" #游戏合约地址
startAddr: "************************************" #顶级节点地址
sendAddr: "************************************" #授权地址
sendAddrPk: "************************************"
gasPrice: 5000000000 # Gas Price越高,交易优先级越高,打包交易速度越快。
gasLimit: 1500000 # Gas Limit 是用户愿意为执行某个操作或确认交易支付的最大Gas量(最少21,000)
isAddGas: false #是否启用按当前市价进行加权矿工费用
addGas: 2000000000 #所增加费用
url: "https://mainnet.infura.io/d75c50732022222222222222222222" #正式网 or 测试网
创建java服务接口
import org.web3j.abi.datatypes.Type;
import java.math.BigInteger;
import java.util.List;
public interface IBaseWeb3j {
String transact(String fromAddr, String fromPrivateKey, String hashVal, String month, BigInteger gasPrice, BigInteger gasLimit, List<Type> inputParameters);
}
实现类
import com.alibaba.fastjson.JSONObject;
import com.blockchain.server.contractGzhz.web3j.IBaseWeb3j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.web3j.abi.FunctionEncoder;
import org.web3j.abi.TypeReference;
import org.web3j.abi.datatypes.Bool;
import org.web3j.abi.datatypes.Function;
import org.web3j.abi.datatypes.Type;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.RawTransaction;
import org.web3j.crypto.TransactionEncoder;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.methods.response.*;
import org.web3j.protocol.http.HttpService;
import org.web3j.utils.Numeric;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
@Component
public class BaseWeb3jImpl implements IBaseWeb3j {
private static final Logger LOG = LoggerFactory.getLogger(BaseWeb3jImpl.class);
static Web3j web3j;
@Value("${contract.url}")
private String URL;
@Value("${contract.addGas}")
private BigInteger addGas;
@Value("${contract.isAddGas}")
private boolean isAddGas;
public String transact(String fromAddr, String fromPrivateKey, String hashVal, String month, BigInteger gasPrice, BigInteger gasLimit, List<Type> inputParameters) {
EthSendTransaction ethSendTransaction = null;
BigInteger nonce = BigInteger.ZERO;
String hash = null;
try {
if(web3j == null){
web3j = Web3j.build(new HttpService(URL));
}
EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(
fromAddr,
DefaultBlockParameterName.PENDING
).send();
//根据配置是否开启根据实时市场gas费用,增加指定gas费用,加快打包速率
if(isAddGas){
BigInteger gas = web3j.ethGasPrice().send().getGasPrice();
LOG.info("获取到的gasPrice{}",gas);
gasPrice = addGas.add(gas);
}
//返回指定地址发生的交易数量。
nonce = ethGetTransactionCount.getTransactionCount();
List outputParameters = new ArrayList();
TypeReference<Bool> typeReference = new TypeReference<Bool>() {
};
outputParameters.add(typeReference);
LOG.info("付给矿工的gasPrice为:{}",gasPrice);
Function function = new Function(
month,
inputParameters,
outputParameters);
String encodedFunction = FunctionEncoder.encode(function);
Credentials credentials = Credentials.create(fromPrivateKey);
RawTransaction rawTransaction = RawTransaction.createTransaction(nonce, gasPrice, gasLimit, hashVal,
encodedFunction);
byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
String hexValue = Numeric.toHexString(signedMessage);
ethSendTransaction = web3j.ethSendRawTransaction(hexValue).sendAsync().get();
hash = ethSendTransaction.getTransactionHash();
LOG.info(JSONObject.toJSONString(ethSendTransaction));
} catch (Exception e) {
if (null != ethSendTransaction) {
LOG.info("失败的原因:" + ethSendTransaction.getError().getMessage());
LOG.info("参数:fromAddr = " + fromAddr);
LOG.info("参数:month = " + month);
LOG.info("参数:gasPrice = " + gasPrice);
LOG.info("参数:gasLimit = " + gasLimit);
LOG.info("参数:inputParameters = " + JSONObject.toJSONString(inputParameters));
}
e.printStackTrace();
}
return hash;
}
调用层
import com.blockchain.server.contractGzhz.service.SettlementService;
import com.blockchain.server.contractGzhz.web3j.IBaseWeb3j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.web3j.abi.datatypes.Type;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
@Component
public class SettlementServiceImpl {
private static final Logger LOG = LoggerFactory.getLogger(SettlementServiceImpl.class);
@Value("${contract.ctAddr}")
private String ctAddr;
@Value("${contract.startAddr}")
private String startAddr;
@Value("${contract.sendAddr}")
private String sendAddr;
@Value("${contract.sendAddrPk}")
private String sendAddrPk;
@Value("${contract.gasLimit}")
private BigInteger CT_GAS_LIMIT;
@Value("${contract.gasPrice}")
private BigInteger CT_GAS_PRICE;
@Autowired
IBaseWeb3j iBaseWeb3j;
public void test() {
try {
List<Type> inputParameters = Arrays.asList( );
iBaseWeb3j.transact(sendAddr,sendAddrPk,ctAddr,"month_name", CT_GAS_PRICE, CT_GAS_LIMIT,inputParameters);
}catch (Exception ex){
LOG.error("发生异常",ex);
}
}
墨迹一下贴一下看官可能用得上的文档
- 链上当前实时油费 :
https://www.ethgasstation.info/txPoolReport.php
- 以太坊开发RPC手册:
http://cw.hubwiz.com/card/c/ethereum-json-rpc-api/1/3/10/