java调用以太坊私链上的合约方法

2024-07-29 18:43:15 浏览数 (1)

使用 java调用以太坊私链上的合约方法

引入java依赖 pom

代码语言:javascript复制
        <!--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

代码语言:javascript复制
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服务接口

代码语言:javascript复制
import org.web3j.abi.datatypes.Type;

import java.math.BigInteger;
import java.util.List;

/**
 * @Datetime: 2020/6/23   10:35
 * @Author:   
 * @title
 */

public interface IBaseWeb3j {

    /**
     * 执行合约打包
     *
     * @param fromAddr        支付地址
     * @param fromPrivateKey  支付地址私钥
     * @param hashVal         合约地址
     * @param month           合约方法
     * @param gasPrice        旷工费用
     * @param inputParameters 方法参数
     * @return hash
     */
    String transact(String fromAddr, String fromPrivateKey, String hashVal, String month, BigInteger gasPrice, BigInteger gasLimit, List<Type> inputParameters);


}

实现类

代码语言:javascript复制
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;

/**
 * @Datetime: 2020/6/23   10:36
 * @Author: 
 * @title
 */

@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;
    }

调用层

代码语言:javascript复制
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;

/**
 * @Datetime: 2020/6/23   11:47
 * @Author:
 * @title
 */
@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/

0 人点赞