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<Type> inputParameters = new ArrayList<>();
|
List<TypeReference<?>> outputParameters = new ArrayList<>();
|
TypeReference<Uint256> typeReference = new TypeReference<Uint256>() {
|
};
|
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<Type> 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<?, EthBlockNumber> 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();
|
}
|
}
|
|
}
|