java使用web3J进行代币转账、余额查询

 <!-- io常用工具类 -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>

        <dependency>
            <groupId>org.web3j</groupId>
            <artifactId>core</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.web3j</groupId>
            <artifactId>geth</artifactId>
            <version>3.2.0</version>
        </dependency>

        <!-- web3j -->
        <dependency>
            <groupId>org.web3j</groupId>
            <artifactId>web3j-spring-boot-starter</artifactId>
            <version>1.6.0</version>
        </dependency>
public static void main(String[] args) {
        /*SpringApplication.run(LongApplication.class, args);
        System.out.printf("启动成功");*/
        // 转出地址
        String from = "0x9175F9EcBbddC078e40C5e037AD31F4abf36628a";
        //转入地址
        String to = "0xa7B049d3A19796B195B0e976ec43EB7a12f07Bf9";
        //转入数量
        String value = "5";
        //转出地址私钥
        String privateKey ="";
        //合约地址
        String contractAddress="0x57E0297510fA155eF165646c208C495E563B3342";
        //位数,根据合约里面的来
        int decimal=4;
        tokenDeal(from,to,value,privateKey,contractAddress,decimal);
    }


    public static String tokenDeal(String from, String to, String value, String privateKey, String contractAddress, int decimal) {
        Web3j web3j = Web3j.build(new HttpService("https://ropsten.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161"));
        try {
            //转账的凭证,需要传入私钥
            Credentials credentials = Credentials.create(privateKey);
            //获取交易笔数
            BigInteger nonce;
            EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(from, DefaultBlockParameterName.PENDING).send();
            if (ethGetTransactionCount == null) {
                return null;
            }
            nonce = ethGetTransactionCount.getTransactionCount();
            //手续费
            BigInteger gasPrice;
            EthGasPrice ethGasPrice = web3j.ethGasPrice().sendAsync().get();
            if (ethGasPrice == null) {
                return null;
            }
            gasPrice = ethGasPrice.getGasPrice();
            //注意手续费的设置,这块很容易遇到问题
            BigInteger gasLimit = BigInteger.valueOf(60000L);

            BigInteger val = new BigDecimal(value).multiply(new BigDecimal("10").pow(decimal)).toBigInteger();// 单位换算
            Function function = new Function(
                    "transfer",
                    Arrays.asList(new Address(to), new Uint256(val)),
                    Collections.singletonList(new TypeReference<Type>() {
                    }));
            //创建交易对象
            String encodedFunction = FunctionEncoder.encode(function);
            RawTransaction rawTransaction = RawTransaction.createTransaction(nonce, gasPrice, gasLimit,
                    contractAddress, encodedFunction);

            //进行签名操作
            byte[] signMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
            String hexValue = Numeric.toHexString(signMessage);
            //发起交易
            EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).sendAsync().get();
            String hash = ethSendTransaction.getTransactionHash();
            if (hash != null) {
                //执行业务
                System.out.printf("执行成功:"+hash);
                return hash;
            }
        } catch (Exception ex) {
            //报错应进行错误处理
            ex.printStackTrace();
        }
        return null;
    }

 查询余额

public static void main(String[] args) {
        //查询的钱包地址
        String from = "0x9175F9EcBbddC078e40C5e037AD31F4abf36628a";
        //合约地址
        String contractAddress="0x57E0297510fA155eF165646c208C495E563B3342";
        //合约部署节点
        Web3j web3j = Web3j.build(new HttpService("https://ropsten.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161"));
        try {
            String code = getERC20Balance(web3j,from,contractAddress);
            System.out.printf("查询出来的余额:"+code);
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    private static final BigDecimal WEI = new BigDecimal(10000);
    /**
     * 获取ERC-20 token指定地址余额
     *
     * @param address         查询地址
     * @param contractAddress 合约地址
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public static String getERC20Balance(Web3j web3j, String address, String contractAddress) throws ExecutionException, InterruptedException {
        String methodName = "balanceOf";
        List<Type> inputParameters = new ArrayList<>();
        List<TypeReference<?>> outputParameters = new ArrayList<>();
        Address fromAddress = new Address(address);
        inputParameters.add(fromAddress);

        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(address, contractAddress, data);

        EthCall ethCall;
        BigDecimal balanceValue = BigDecimal.ZERO;
        try {
            ethCall = web3j.ethCall(transaction, DefaultBlockParameterName.LATEST).send();
            List<Type> results = FunctionReturnDecoder.decode(ethCall.getValue(), function.getOutputParameters());
            Integer value = 0;
            if(results != null && results.size()>0){
                value = Integer.parseInt(String.valueOf(results.get(0).getValue()));
            }
            balanceValue = new BigDecimal(value).divide(WEI, 6, RoundingMode.HALF_DOWN);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return balanceValue.toString();
    }


版权声明:本文为qq_38935605原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。