天天看點

以太坊或ERC20轉賬查詢(Java版本)工具類

表現效果

測試用例 EthTestData.java

/**
 * 測試資料
 *
 * @Autor Tricky
 * @Date 2021-04-01 22:06:36
 */

public class EthTestData {
//    {"address":"0xe81128942ed67a3b453576cad44fa9fb7f0b2098","privateKey":"8ca3edaabc0567d9555ade455bab24a27bea6ee0524e96ffac9a3cfc2b841214"}
    private String privateKey="8ca3edaabc0567d9555ade455bab24a27bea6ee0524e96ffac9a3cfc2b841214";

    private String myAddress = "0xab8ba39195bFF4D406FC62A776ce41dBA6FCf1fD";
    //rinkeby上面的測試币 erc20-usdt同款
    private String contract="0xf805ed280cadeadc2aa135808688e06fef5a9b71";

    private Web3j web3j ;

    {
        try{
        //如果這個位址不知道怎麼擷取 可以參考  https://blog.csdn.net/sail331x/article/details/115395131
            web3j = Web3j.build(new HttpService("https://rinkeby.infura.io/v3/dddddddddda74486b59041e5d83f4af1"));
        }catch (Throwable t){
            t.printStackTrace();
        }
    }

    /**
     * 建立位址
     */
    @Test
    public void createAddress(){
        System.out.println("建立位址:"+JSONUtil.toJsonStr(EthUtils.createAddress()));
    }

    /**
     * 查詢eth數量
     */
    @Test
    public void balanceOf(){
        System.out.println("查詢ETH:"+EthUtils.balanceOf(web3j,myAddress));
    }

    /**
     * 查詢ERC20數量
     */
    @Test
    public void balanceOfErc20(){
        System.out.println("查詢ERC20:"+EthUtils.balanceOfErc20(web3j,contract,myAddress));
    }

    /**
     * 發送ERC20
     */
    @Test
    public void sendErc20(){
        String txid = EthUtils.sendErc20(web3j, contract, privateKey, myAddress, BigInteger.valueOf(10000000));
        System.out.println("發送ERC20:"+txid);
    }

    /**
     * 發送以太坊
     */
    @Test
    public void sendEth(){
        String txid = EthUtils.sendEth(web3j, privateKey, myAddress, new BigDecimal("0.001"));
        System.out.println("發送ETH:"+txid);
    }

    @Test
    public void getTransaction(){
        //合約
        String txid="0x29d96b351be4ab1c29912a1c26c1c8f9205fc35fb9ea2395c53c5c2e1884c421";
        //eth
        String txid2="0xef3c06f56085187d6a43edec2bb399a7fe98572aad63bcd5bd80e5e5dab153b3";
        EthTransaction tx = EthUtils.getTransaction(web3j, txid2);
        System.out.println("查詢交易:"+JSONUtil.toJsonStr(tx));
    }
}
           
運作結果
以太坊或ERC20轉賬查詢(Java版本)工具類

工具類

EthUtils.java工具類

/**
 * 以太坊工具類
 *
 * @Autor Tricky
 * @Date 2021-04-01 21:02:11
 */
@Slf4j
public class EthUtils {

    public static final BigDecimal ETH_DECIMALS = new BigDecimal(1_000_000_000_000_000_000L);

    public static final BigInteger ETH_GAS_LIMIT = new BigInteger("100000");

    /**
     * 擷取區塊資料
     *
     * @param web3j
     * @param block                  塊高
     * @param fullTransactionObjects 是否需要交易資料
     * @return
     */
    public static EthBlock getBlock(Web3j web3j, long block, boolean fullTransactionObjects) {
        try {
            return web3j.ethGetBlockByNumber(new DefaultBlockParameterNumber(block), fullTransactionObjects).send();
        } catch (Throwable t) {
            logger.error(String.format("Get Block Error %d", block), t);
        }
        return null;
    }

    /**
     * 擷取目前塊高
     *
     * @param web3j
     * @return
     */
    public static long getNowBlockNumber(Web3j web3j) {
        try {
            EthBlockNumber send = web3j.ethBlockNumber().send();
            return send.getBlockNumber().longValue();
        } catch (Throwable t) {
            logger.error("GetBlockNumberError", t);
        }
        return -1;
    }

    /**
     * 發送erc20
     *
     * @param web3j
     * @param contractAddress 合約位址
     * @param privateKey      私鑰
     * @param to              收款位址
     * @param value           額度
     * @return
     */
    public static String sendErc20(Web3j web3j, String contractAddress, String privateKey,
                                   String to, BigInteger value) {
        String from = getAddressByPrivateKey(privateKey);
        logger.info(String.format("Start:SendErc20 from:%s to:%s amount:%s erc20:%s", from, to, value.toString(), contractAddress));
        try {
            //加載轉賬所需的憑證,用私鑰
            Credentials credentials = Credentials.create(privateKey);
            //擷取nonce,交易筆數
            BigInteger nonce = getNonce(web3j, from);
            if (nonce == null) {
                logger.error(String.format("END:GetNonceError from:%s to:%s amount:%s erc20:%s", from, to, value.toString(), contractAddress));
                return null;
            }
            //gasPrice和gasLimit 都可以手動設定
            BigInteger gasPrice = getGasPrice(web3j);
            if (gasPrice == null) {
                logger.error(String.format("END:GetGasPriceError from:%s to:%s amount:%s erc20:%s", from, to, value.toString(), contractAddress));
                return null;
            }
            //BigInteger.valueOf(4300000L) 如果交易失敗 很可能是手續費的設定問題
            BigInteger gasLimit = BigInteger.valueOf(60000L);
            //ERC20代币合約方法
            Function function = new Function(
                    "transfer",
                    Arrays.asList(new Address(to), new Uint256(value)),
                    Collections.singletonList(new TypeReference<Type>() {
                    }));
            //建立RawTransaction交易對象
            String encodedFunction = FunctionEncoder.encode(function);
            RawTransaction rawTransaction = RawTransaction.createTransaction(nonce, gasPrice, gasLimit,
                    contractAddress, encodedFunction);

            //簽名Transaction
            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) {
                return hash;
            }
            logger.error(String.format("END:HashIsNull from:%s to:%s amount:%s erc20:%s", from, to, value.toString(), contractAddress));
        } catch (Throwable t) {
            logger.error(String.format("發送ERC20失敗 from=%s to=%s erc20=%s amount=%s",
                    from, to, contractAddress, value.toString()), t);
        }
        return null;
    }

    /**
     * 列出交易資訊
     *
     * @param block  區塊高度
     * @param filter 過濾器
     * @return
     */
    public static List<EthBlock.TransactionResult> getTransactions(Web3j web3j, long block, java.util.function.Function<EthBlock.TransactionResult, Boolean> filter) {
        EthBlock send = getBlock(web3j, block, true);
        if (send == null) {
            logger.error(String.format("GetBlockDataError:%d", block));
            return Collections.emptyList();
        }
        List<EthBlock.TransactionResult> transactions = send.getBlock().getTransactions();
        if (filter != null) {
            List<EthBlock.TransactionResult> result = new ArrayList<>();
            for (EthBlock.TransactionResult e : transactions) {
                try {
                    if (filter.apply(e)) {
                        result.add(e);
                    }
                } catch (Throwable t) {
                    logger.error(t.getMessage(), t);
                }
            }
            return result;
        }
        return transactions;

    }

    /**
     * 根據私鑰擷取位址
     *
     * @param privateKey
     * @return
     */
    public static String getAddressByPrivateKey(String privateKey) {
        ECKeyPair ecKeyPair = ECKeyPair.create(new BigInteger(privateKey, 16));
        return "0x" + Keys.getAddress(ecKeyPair).toLowerCase();
    }


    /**
     * 建立位址
     *
     * @return
     */
    public static EthAddress createAddress() {
        try {
            String seed = UUID.randomUUID().toString();
            ECKeyPair ecKeyPair = Keys.createEcKeyPair();
            BigInteger privateKeyInDec = ecKeyPair.getPrivateKey();

            String sPrivatekeyInHex = privateKeyInDec.toString(16);

            WalletFile aWallet = Wallet.createLight(seed, ecKeyPair);
            String sAddress = aWallet.getAddress();

            EthAddress address = new EthAddress();
            address.setAddress("0x" + sAddress);
            address.setPrivateKey(sPrivatekeyInHex);
            return address;
        } catch (Throwable t) {
            logger.error("建立位址失敗", t);
        }
        return null;
    }

    /**
     * 查詢位址以太坊數量
     *
     * @param web3j
     * @param address 查詢位址
     * @return
     */
    public static BigDecimal balanceOf(Web3j web3j, String address) {
        try {
            EthGetBalance balance = web3j.ethGetBalance(address, DefaultBlockParameterName.LATEST).send();
            BigInteger amount = balance.getBalance();
            if (amount == null || amount.compareTo(BigInteger.ZERO) <= 0) {
                return BigDecimal.ZERO;
            }
            return new BigDecimal(amount).divide(ETH_DECIMALS, 18, RoundingMode.FLOOR);
        } catch (Throwable t) {
            logger.error(String.format("擷取以太坊數量出錯 %s", address), t);
        }
        return BigDecimal.ZERO;
    }


    /**
     * 轉換成最小機關 Wei
     *
     * @param ethAmount
     * @return
     */
    public static BigInteger toWei(BigDecimal ethAmount) {
        return ethAmount.multiply(ETH_DECIMALS).toBigInteger();
    }

    /**
     * wei to eth
     *
     * @param wei
     * @return
     */
    public static BigDecimal toEth(BigInteger wei) {
        return new BigDecimal(wei).divide(ETH_DECIMALS, 18, RoundingMode.FLOOR);
    }

    /**
     * 查詢erc20的餘額
     *
     * @param web3j
     * @param contract 合約位址
     * @param address  查詢位址
     * @return
     */
    public static BigInteger balanceOfErc20(Web3j web3j, String contract, String address) {
        try {
            final String DATA_PREFIX = "0x70a08231000000000000000000000000";
            String value = web3j.ethCall(org.web3j.protocol.core.methods.request.Transaction.createEthCallTransaction(address,
                    contract, DATA_PREFIX + address.substring(2)), DefaultBlockParameterName.PENDING).send().getValue();
            if (StrUtil.isEmptyIfStr(value)) {
                return BigInteger.ZERO;
            }
            return new BigInteger(value.substring(2), 16);
        } catch (Throwable t) {
            logger.error(String.format("查詢ERC20失敗 contract:%s address:%s", contract, address), t);
        }
        return BigInteger.ZERO;
    }

    /**
     * 擷取gas-price
     *
     * @param web3j
     * @return
     */
    public static BigInteger getGasPrice(Web3j web3j) {
        try {
            EthGasPrice ethGasPrice = web3j.ethGasPrice().sendAsync().get();
            if (ethGasPrice == null) {
                logger.error("GetGasPriceError");
                return null;
            }
            return ethGasPrice.getGasPrice();
        } catch (Throwable t) {
            logger.error(t.getMessage(), t);
        }
        return null;
    }

    /**
     * 擷取nonce
     *
     * @param web3j
     * @param address
     * @return
     */
    public static BigInteger getNonce(Web3j web3j, String address) {
        try {
            EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(address, DefaultBlockParameterName.PENDING).send();
            if (ethGetTransactionCount == null) {
                logger.error("GetNonceError:" + address);
                return null;
            }
            return ethGetTransactionCount.getTransactionCount();
        } catch (Throwable t) {
            logger.error("GetNonceError:" + address);
        }
        return null;
    }

    /**
     * 發送以太坊
     *
     * @param web3j
     * @param privateKey 發送者私鑰
     * @param to         收款位址
     * @param wei        wei為機關的數量
     * @param gasPrice   gas-price
     * @param gasLimit   gas-limit
     * @return
     */
    public static String sendEth(Web3j web3j, String privateKey, String to, BigInteger wei, BigInteger gasPrice, BigInteger gasLimit) {
        String from = getAddressByPrivateKey(privateKey);
        try {
            //加載轉賬所需的憑證,用私鑰
            Credentials credentials = Credentials.create(privateKey);
            //擷取nonce,交易筆數
            BigInteger nonce = getNonce(web3j, from);
            //建立RawTransaction交易對象
            RawTransaction rawTransaction = RawTransaction.createEtherTransaction(nonce, gasPrice, gasLimit, to, wei);
            //簽名Transaction,這裡要對交易做簽名
            byte[] signMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
            String hexValue = Numeric.toHexString(signMessage);
            //發送交易
            EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).sendAsync().get();
            return ethSendTransaction.getTransactionHash();
        } catch (Throwable t) {
            logger.error(String.format("發送ETH失敗 from:%s to:%s amount-eth:%s", from, to, toEth(wei).toString()));
        }
        return null;
    }

    /**
     * 發送以太坊
     *
     * @param web3j
     * @param privateKey 發送者私鑰
     * @param to         收款位址
     * @param wei        wei為機關的數量
     * @return
     */
    public static String sendEth(Web3j web3j, String privateKey, String to, BigInteger wei) {
        return sendEth(web3j, privateKey, to, wei, getGasPrice(web3j), ETH_GAS_LIMIT);
    }

    /**
     * 發送以太坊
     *
     * @param web3j
     * @param privateKey 發送者私鑰
     * @param to         收款位址
     * @param eth        wei為機關的數量
     * @param gasPrice   gas-price
     * @param gasLimit   gas-limit
     * @return
     */
    public static String sendEth(Web3j web3j, String privateKey, String to, BigDecimal eth, BigInteger gasPrice, BigInteger gasLimit) {
        return sendEth(web3j, privateKey, to, toWei(eth), gasPrice, gasLimit);
    }

    /**
     * 發送以太坊
     *
     * @param web3j
     * @param privateKey 發送者私鑰
     * @param to         收款位址
     * @param eth        wei為機關的數量
     * @return
     */
    public static String sendEth(Web3j web3j, String privateKey, String to, BigDecimal eth) {
        return sendEth(web3j, privateKey, to, toWei(eth), getGasPrice(web3j), ETH_GAS_LIMIT);
    }

    /**
     * 根據hash擷取交易資訊
     * @param web3j
     * @param hash
     * @return
     */
    public static EthTransaction getTransaction(Web3j web3j, String hash) {
        try {
            EthTransaction tx = web3j.ethGetTransactionByHash(hash).send();
            return tx;
        } catch (Throwable t) {
            logger.error("GetTransactionError:" + hash, t);
        }
        return null;
    }
}

           

寫在最後

注意 這裡的Web3j初始化用的url 可以到 https://infura.io/ 中去申請。

以太坊(ETH)發行ERC20代币(Rinkeby示範)

波場歸集充值回調(trx/trc10/trc20版本整合)

tron(波場)trc20離線簽名廣播交易(Java版本)

如有任何問題或者寫得不對的地方 歡迎留言評論指點下哦

繼續閱讀