package cc.mrbird.febs.mall.chain.ercCoin; import org.web3j.abi.FunctionEncoder; import org.web3j.abi.FunctionReturnDecoder; import org.web3j.abi.TypeReference; import org.web3j.abi.datatypes.Function; import org.web3j.abi.datatypes.Type; import org.web3j.abi.datatypes.generated.Uint256; import org.web3j.protocol.Web3j; import org.web3j.protocol.core.DefaultBlockParameterName; import org.web3j.protocol.core.Request; import org.web3j.protocol.core.methods.request.Transaction; import org.web3j.protocol.core.methods.response.EthBlockNumber; import org.web3j.protocol.core.methods.response.EthCall; import org.web3j.protocol.http.HttpService; import org.web3j.utils.Numeric; import java.io.IOException; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; public class EthService implements ContractChainService { private Web3j web3j; private String url; private String ownerAddress; private String privateKey; private String contractAddress; public EthService(String url, String address, String privateKey, String contractAddress) { this.url = url; this.ownerAddress = address; this.privateKey = privateKey; this.contractAddress = contractAddress; HttpService service = new HttpService(url); web3j = Web3j.build(service); } @Override public int decimals() { try { String methodName = "decimals"; List inputParameters = new ArrayList<>(); List> outputParameters = new ArrayList<>(); TypeReference typeReference = new TypeReference() { }; outputParameters.add(typeReference); Function function = new Function(methodName, inputParameters, outputParameters); String data = FunctionEncoder.encode(function); Transaction transaction = Transaction.createEthCallTransaction(null, contractAddress, data); EthCall ethCall; BigInteger decimals = BigInteger.ZERO; try { ethCall = web3j.ethCall(transaction, DefaultBlockParameterName.LATEST).send(); List results = FunctionReturnDecoder.decode(ethCall.getValue(), function.getOutputParameters()); decimals = (BigInteger) results.get(0).getValue(); return decimals.intValue(); } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } return 0; } @Override public BigInteger blockNumber() { Request request = web3j.ethBlockNumber(); EthBlockNumber send = null; try { send = request.send(); } catch (IOException e) { e.printStackTrace(); } if (send != null) { return Numeric.decodeQuantity(send.getResult()); } else { throw new NullPointerException(); } } }