1. To query through web3j

The Ropsten test network is used here

1. Connect the Ethernet network

The first step for Web3J to connect to Ethernet is to have an Ethernet client (such as a local client, or a cloud client), which Web3J recommends using infura’s cloud client

Web3j Web3j = web3j.build (new HttpService(” ropst.infura. IO /mew”)); Here the token is mew, the token of MyEtherWallet in Infura

I’m using infura’s cloud client here. I can go to Infura and register my token, and then I can connect to the Ethereum network

2. Obtain a Java implementation of the ERC20 contract, where Web3j is implemented via the web3j built-in command-line tool (requires contract binaries and abi interface)

/*TODO has a problem obtaining bin from the compiler

For example, I wrote a contract on an online compiler called remix.ethereum.org (to see the binaries and abi interface of the contract, select Details in the right-hand side of remix)*/

In fact, after publishing the contract, you should verify the contract code in the blockchain browser (Tetherscan.io), and when the verification is successful, you will see the binary code created for the contract under the ABI file, where the binary code is complete, and then the generated contract object passes Contract object. IsValid (), which returns true to validate

Bat is not double-click to enter the file location. Press enter web3j.bat. If the web3j. IO icon is displayed, it indicates that the file is successful.

For example: Java objects that need to be generated by the Web3j command line tool * need to get the binary code of the contract saved: name. bin * Need to get the ABI data of the contract saved: name. abi

-o is the folder name of the output

-p behind is to save the package name * command instances: web3j solidity generate TokenDemo. Bin TokenDemo. Abi – o/Java – p com.your.org anisation. Name

  1. Gets the query object balance
package test; import java.io.IOException; import java.math.BigDecimal; import java.math.BigInteger; import org.web3j.crypto.Credentials; import org.web3j.protocol.Web3j; import org.web3j.protocol.admin.Admin; import org.web3j.protocol.core.DefaultBlockParameterName; import org.web3j.protocol.core.RemoteCall; import org.web3j.protocol.http.HttpService; import org.web3j.tx.Contract; import contract.MttContract; /** * Obtain user wallet address balance, including smart contract address balance */ public class TestGetBalance {/** * Query Ether * @param args * @throws Exception */ public static void main(String[] args) throws Exception { Web3j web3j = getWeb3j(StaticValue.ropstenService); getEthBanlance(web3j,StaticValue.account2); / / specify the purse for specified currency balance Contract erc20Contract = getERC20Contract (web3j, StaticValue MttContractAddress, StaticValue.account2Pri); GetERC20Balance (web3j erc20Contract, StaticValue account2, 8). close(web3j); } /** * connect to the network * @param netUrl * @return */ public static Web3j getWeb3j(String netUrl){Admin Web3j = Admin HttpService(netUrl)); return web3j; } @param web3j */ public static void close(web3j web3j){web3j. Shutdown (); } /** * Querying the balance of The Ethernet account * @throws IOException */ public static String getEthBanlance(Web3j Web3j,String userAddress) throws IOException {// Get the ether balance BigInteger for the specified wallet integer=web3j.ethGetBalance(userAddress,DefaultBlockParameterName.LATEST).send().getBalance(); String decimal = toDecimal(18,integer); System.out.println(decimal); /*String STR = integer.tostring (); /*String STR = integer.tostring (); String decimal = toDecimal(18,str); System.out.println(decimal); */ return decimal; } @return */ public static Contract getERC20Contract(Web3j Web3j,String contractAddress,String userPri){ BigInteger GAS_PRICE = BigInteger.valueOf(22_000_000_000L); BigInteger GAS_LIMIT = BigInteger.valueOf(4_300_000); Credentials credentials = Credentials.create(userPri); MttContract contract = mttcontract. load(contractAddress, web3j, credentials, GAS_PRICE, GAS_LIMIT); return contract; } /** * Query erC 20 token price * @throws Exception */ public static String getERC20Balance(Web3j Web3j,Contract Contract,String) userAddress,int decimal) throws Exception{ // Web3ClientVersion web3ClientVersion = web3j.web3ClientVersion().send(); // Send is a synchronous request // Web3ClientVersion Web3ClientVersion = web3.web3ClientVersion().sendAsync().get(); //sendAsync(), sending asynchronous requests with CompletableFuture (Future on Android) :  // String clientVersion = web3ClientVersion.getWeb3ClientVersion(); // System.out.println(clientVersion); // RxJava Observable: /*Web3j web3 = web3j.build (new HttpService()); // defaults to http://localhost:8545/ web3.web3ClientVersion().observable().subscribe(x -> { String clientVersion = x.getWeb3ClientVersion(); . }); */ RemoteCall<BigInteger> balanceOf = ((MttContract) contract).balanceOf(userAddress); BigInteger send2 = balanceOf.send(); String result = toDecimal(8, send2); System.out.println(result); return result; * @param decimal * @param STR * @return */ public static String toDecimal(int) decimal,BigInteger integer){ // String substring = str.substring(str.length() - decimal); StringBuffer sbf = new StringBuffer("1"); for (int i = 0; i < decimal; i++) { sbf.append("0"); } String balance = new BigDecimal(integer).divide(new BigDecimal(sbf.toString()), 18, BigDecimal.ROUND_DOWN).toPlainString(); return balance; }}Copy the code

StaticValue.class

package test; public class StaticValue { public static final String ropstenService = "https://ropsten.infura.io/mew"; Public static final String account1 = "address of my test wallet "; Public static final String account2 = "account2 "; Public static final String account1Pri = "my test wallet address 1 private key "; Public static final String account2Pri = "account2Pri "; Public static final String MttContractAddress = "ErC20 contractAddress "; }Copy the code

2. Query the ERC20 token balance through the etherscan. IO interface

Decimal is the precision specified when the contract is created, where the URL refers to the network to which Etherscan is connected, such as the Ropsten test network: api-ropst.etherscan. IO/API

Apikey is the token obtained in etherscan,contractAddress is the contractAddress,address account address,

Okhttp3 is displayed, and Jackson 2.8.5 is used to process the RESULTING JSON

/** * https://api.etherscan.io/api? module=account&action=tokenbalance&contractaddress=0x57d90b64a1a57749b0f932f1a3395792e12e7055&address=0xe04f27eb70e025b7 8871a2ad7eabe85e61212761&tag= latest&ApiKey =YourApiKeyToken * Query account ERC20 token balance * @param URL * @param contractAddress * @param address * @param decimal * @return */ public static String getERC20Balance(String url,String contractAddress,String address,int decimal){ TreeMap<String,String> treeMap = new TreeMap<>(); treeMap.put("module", "account"); treeMap.put("action", "tokenbalance"); treeMap.put("contractaddress", contractAddress); treeMap.put("address", address); treeMap.put("tag", "latest"); treeMap.put("apikey", StaticValue.etherscanToken); StringBuffer sbf = new StringBuffer(); for (String str : treeMap.keySet()) { sbf.append(str).append("=").append(treeMap.get(str)).append("&"); } url = url.concat("?" ).concat(sbf.substring(0, sbf.length() - 1)); Object send = send(url); return TestUtil.toDecimal(decimal,new BigInteger(String.valueOf(send))); } /** * Get ether price * @param URL * @return */ public static String getEthPrice(String URL){TreeMap<String,String> TreeMap =  new TreeMap<>(); treeMap.put("module", "stats"); treeMap.put("action", "ethprice"); treeMap.put("apikey", StaticValue.etherscanToken); StringBuffer sbf = new StringBuffer(); for (String str : treeMap.keySet()) { sbf.append(str).append("=").append(treeMap.get(str)).append("&"); } url = url.concat("?" ).concat(sbf.substring(0, sbf.length() - 1)); Object send = send(url); return String.valueOf(send); } public static Object send(String url){ String responseMessageGet = TestOKHttp.getResponseMessageGet(url); ObjectMapper mapper = new ObjectMapper(); Map<String,String> reMap = null; try { reMap = mapper.readValue(responseMessageGet, new TypeReference<Map<String,Object>>(){}); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return reMap.get("result"); }Copy the code

The Decimal method is converted to precision. Ethereum defaults to 18, but other tokens do not.

* @param decimal * @param STR * @return */ public static String toDecimal(int Decimal,BigInteger  integer){ // String substring = str.substring(str.length() - decimal); StringBuffer sbf = new StringBuffer("1"); for (int i = 0; i < decimal; i++) { sbf.append("0"); } String balance = new BigDecimal(integer).divide(new BigDecimal(sbf.toString()), 18, BigDecimal.ROUND_DOWN).toPlainString(); return balance; }Copy the code

TestOKHttp class

Public static ResponseBody testGetClient(String URL){OkHttpClient okClient = new OkHttpClient();  Request request = new Request.Builder() .get().url(url).build(); ResponseBody resBody = null; try { Response response = okClient.newCall(request).execute(); resBody = response.body(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return resBody; } public static String getResponseMessageGet(String url) { ResponseBody body = null; String string = null; body = testGetClient(url); if(checkEmpty(body)) return null; try { string = body.string(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return string; } public static boolean checkEmpty(Object obj){ if(null! =obj && ! obj.toString().trim().equals("")){ return false; } return true; }Copy the code

Please indicate where to reprint