以太坊或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 = "0x6B488606b33a254734F17797Ab42fc03C8c3Ce73";
    //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));
    }
}
运行结果

在这里插入图片描述


工具类

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版本)

如有任何问题或者写得不对的地方 欢迎留言评论指点下哦

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
ERC20是以太坊上的代币标准,Java可以通过以太坊的API(如web3j)来与以太坊进行交互,实现授权转账的代码如下: 1. 授权 ```java //导入web3j相关的类 import org.web3j.abi.datatypes.Address; import org.web3j.abi.datatypes.generated.Uint256; import org.web3j.protocol.Web3j; import org.web3j.protocol.core.DefaultBlockParameterName; import org.web3j.protocol.core.methods.response.TransactionReceipt; import org.web3j.tx.Contract; import org.web3j.tx.ManagedTransaction; import org.web3j.tx.TransactionManager; import org.web3j.tx.gas.DefaultGasProvider; //代币合约地址 String contractAddress = "0x12345..."; //代币转账地址 String fromAddress = "0xabcdef..."; //代币接收地址 String toAddress = "0x123456..."; //代币授权数量 BigInteger tokenAmount = BigInteger.valueOf(10000); //创建web3j实例 Web3j web3j = Web3j.build(new HttpService("https://ropsten.infura.io/v3/your-project-id")); //创建交易管理器 TransactionManager transactionManager = new RawTransactionManager(web3j, credentials); //创建代币合约实例 ERC20Token contract = ERC20Token.load(contractAddress, web3j, transactionManager, DefaultGasProvider.GAS_PRICE, DefaultGasProvider.GAS_LIMIT); //授权代币合约 TransactionReceipt approveReceipt = contract.approve(new Address(toAddress), new Uint256(tokenAmount)).send(); ``` 2. 转账 ```java //代币转账数量 BigInteger transferAmount = BigInteger.valueOf(100); //调用代币合约的transferFrom方法实现转账 TransactionReceipt transferReceipt = contract.transferFrom(new Address(fromAddress), new Address(toAddress), new Uint256(transferAmount)).send(); ``` 以上代码中,`ERC20Token`是自定义的Java类,用于与代币合约进行交互,需要根据代币合约的ABI文件生成。具体生成方法可以参考web3j的官方文档。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值