ERC20合约调用DEMO

import org.web3j.abi.FunctionEncoder;
import org.web3j.abi.FunctionReturnDecoder;
import org.web3j.abi.TypeReference;
import org.web3j.abi.datatypes.Address;
import org.web3j.abi.datatypes.Function;
import org.web3j.abi.datatypes.Type;
import org.web3j.abi.datatypes.generated.Uint256;
import org.web3j.crypto.Credentials;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.methods.request.Transaction;
import org.web3j.protocol.core.methods.response.EthCall;
import org.web3j.protocol.core.methods.response.EthGetBalance;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.protocol.http.HttpService;
import org.web3j.tx.Transfer;
import org.web3j.utils.Convert;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.List;
//skate case hard bean stereo cake mistake start slide anchor opinion congress
//https://testnet.bnbchain.org/faucet-smart 测试币地址
//https://testnet.bscscan.com/tx/0x042903ceafd22edcfce7afdbc6d5ba90f46dd95ce1086a8d7b33708d2803d418  区块查询
/**
 * @author zst
 * @description
 * @date 2023/9/16 0016 10:23
 * @mail 804633234@qq.com
 */
public class BiAn {

    //是否是正式节点
    private static String node="false";

    public static void main(String[] args) throws Exception {
        //usdt在币安正式合约地址
        String usdtContractAddress = "0xdAC17F958D2ee523a2206206994597C13D831ec7";
        if(node.equals("false")){
            //usdt在币安测试合约地址
            usdtContractAddress = "0x337610d27c682E347C9cD60BD4b3b107C9d34dDd";
        }
        //测试货币  合约地址  0xb8a0bDDAeb549c37568D953dCc1b54888B269974

        // 测试账户
        String address1 = "0x4417a8AEf1a47Cec34Fe51DD85f816484d3ED682";
        String address1Pri="cf4ae07db02f193ad756e720717a551a6df5cb960e00ff6e0b824ca6054a3187";
        String address2 = "0x0437C0646f3827A6F92e013306f8027024bD087B"; //0.1 bnb
        String address2Pri="94416331c98a5aa6a016057aa1e105310ed69f38730fa49ddd81238ccea26d9e";
        String address3 = "0x27D942be1E5740c9dA4b57b91B0Fc021530F4D6C"; //10 usdt 0.01BNb
        String address3Pri="f9fdc39286c0db83358d69e4c0929feeee6f1dec37423c07f5d7055fd6f77d79";
        String address4 ="0x89867dE0ae3cA7Abea22BeAB564CAEA8f8080ECb"; //0.1eth
        String address4Pri="462d7bf4c1ec28da71841d5478bc876649d95588ce5d57d50bf97d5e033dc82c";
        String address5 ="0x82a155Da19a7f3733CfB7Ae687991D5675505C3C"; //0.1eth
        String address5Pri="2d66316b17c1268a8305a2b7cc72c5a88570578f027f40c07c207814003fb01f";
//        //获取账户余额
//        String balance=getOtherBalance(address3,usdtContractAddress);
//        System.out.println("ERC20:"+balance);
//        //转移BAB
//        String babHash=transferBnb(address5,address1,new BigDecimal("0.001"));
//        getResult(babHash);//获取转账结果
//        //发起转账
//        String hash= erc20Transfer(address3Pri,usdtContractAddress,address1,new BigDecimal("1"));
//        getResult(hash);//获取转账结果
//        //获取bab账户余额
//        String babBalance=   getBabBalance("0x0437C0646f3827A6F92e013306f8027024bD087B");
//        System.out.println("BAB balance:"+babBalance);

        String balance=getOtherBalance(address5,"0xb8a0bDDAeb549c37568D953dCc1b54888B269974");
        System.out.println("ERC20:"+balance);

    }
    public static Web3j setNode(){
        // binan正式节点
        String nodeUrl = "https://bsc.nodereal.io";
        if(node.equals("false")) {
            // bian测试节点
            nodeUrl = "https://data-seed-prebsc-1-s1.bnbchain.org:8545";
        }
        // 连接到币安链网络
        return Web3j.build(new HttpService(nodeUrl));
    }

    /**
     * 获取BAB账户余额
     * @param address
     * @return
     */
    public static String getBabBalance(String address){
        Web3j web3j =setNode();
        // 获取 BNB 余额
        EthGetBalance balanceResponse = null;
        try {
            balanceResponse = web3j.ethGetBalance(address, DefaultBlockParameterName.LATEST).send();
        } catch (IOException e) {
            e.printStackTrace();
        }
        BigInteger balanceWei = balanceResponse.getBalance();
        // 将余额从 Wei 转换为 BNB
        String balanceBNB = Convert.fromWei(balanceWei.toString(), Convert.Unit.ETHER).toPlainString();
        return balanceBNB;
    }

    /**
     * ERC20 获取账户余额
     * @param address
     * @param contractAddress
     */
    public static String  getOtherBalance(String address,String contractAddress){
        Web3j web3j =setNode();
        Function balanceOf = new Function(
                "balanceOf",
                Arrays.asList(new Address(address)),
                Arrays.asList(new TypeReference<Uint256>() {})
        );

        String encodedFunction = FunctionEncoder.encode(balanceOf);
        EthCall response = null;
        try {
            response = web3j.ethCall(
                    Transaction.createEthCallTransaction(address, contractAddress, encodedFunction),
                    DefaultBlockParameterName.LATEST
            ).send();
        } catch (IOException e) {
            e.printStackTrace();
        }

        List<Type> result = FunctionReturnDecoder.decode(response.getValue(), balanceOf.getOutputParameters());
        if(result.size()>0){
            BigInteger balance = (BigInteger) result.get(0).getValue();
            return new BigDecimal(balance).toString();
        }
        return new BigDecimal("0").toString();
    }

    /**
     * ERC20 转账
     * @param privateKey
     * @param contractAddress
     * @param toAddress
     * @param amount
     * @return
     */
    public static String erc20Transfer(String privateKey,String contractAddress,String toAddress,BigDecimal amount ){
        // 连接到币安智能链节点
        Web3j web3j =setNode();
        Credentials credentials = Credentials.create(privateKey);
        // 创建合约实例
        ERC20 Contract = ERC20.load(contractAddress, web3j, credentials, Transfer.GAS_PRICE, BigInteger.valueOf(80000L));
        try {
            // 将余额转换为可读格式
            BigInteger senderBalanceReadable = amount.multiply(Convert.Unit.ETHER.getWeiFactor()).toBigInteger();
            System.out.println("金额:"+senderBalanceReadable);
            TransactionReceipt transactionReceipt = Contract.transfer(toAddress, senderBalanceReadable).send();

            // 转账成功,打印交易哈希值
            String txHash = transactionReceipt.getTransactionHash();
            System.out.println("转账成功!交易哈希值:" + txHash);
            return txHash;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * BAB转账
     * @param toAddress
     * @param privateKey
     * @param amount
     */
    public static String transferBnb(String privateKey,String toAddress,BigDecimal amount){
        Web3j web3j =setNode();
        // 转账操作
        Credentials credentials = Credentials.create(privateKey);
        try {
            TransactionReceipt   transfer = Transfer.sendFunds(web3j, credentials, toAddress, amount, Convert.Unit.ETHER).send();
            return transfer.getTransactionHash();
        } catch (Exception e) {
                e.printStackTrace();
        }
        return null;
    }

    /**
     * hash 查询交易结果
     * @param txHash
     * @return
     */
    public static boolean getResult(String txHash){
        Web3j web3j =setNode();
        try {
            // 查询交易收据
            TransactionReceipt transactionReceipt = web3j.ethGetTransactionReceipt(txHash).send().getTransactionReceipt().orElse(null);
            System.out.println(transactionReceipt);
            if (transactionReceipt != null && transactionReceipt.isStatusOK()) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

}
import org.web3j.abi.TypeReference;
import org.web3j.abi.datatypes.Address;
import org.web3j.abi.datatypes.Function;
import org.web3j.abi.datatypes.generated.Uint256;
import org.web3j.crypto.Credentials;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.RemoteCall;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.tx.Contract;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collections;

public class ERC20 extends Contract {
    private static final String FUNCTION_NAME_TRANSFER = "transfer";
    private static final String FUNCTION_NAME_TRANSFER_FROM = "transferFrom";
    private static final String FUNCTION_NAME_APPROVE = "approve";
    private static final String FUNCTION_NAME_TOTAL_SUPPLY = "totalSupply";
    private static final String FUNCTION_NAME_BALANCE_OF = "balanceOf";
    private static final String EVENT_TRANSFER = "Transfer";

    private ERC20(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {
        super("", contractAddress, web3j, credentials, gasPrice, gasLimit);
    }

    public static ERC20 load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {
        return new ERC20(contractAddress, web3j, credentials, gasPrice, gasLimit);
    }

    public RemoteCall<TransactionReceipt> transfer(String to, BigInteger value) {
        Function function = new Function(
                FUNCTION_NAME_TRANSFER,
                Arrays.asList(new Address(to), new Uint256(value)),
                Collections.emptyList()
        );
        return executeRemoteCallTransaction(function);
    }

    public RemoteCall<TransactionReceipt> transferFrom(String from, String to, BigInteger value) {
        Function function = new Function(
                FUNCTION_NAME_TRANSFER_FROM,
                Arrays.asList(new Address(from), new Address(to), new Uint256(value)),
                Collections.emptyList()
        );
        return executeRemoteCallTransaction(function);
    }

    public RemoteCall<TransactionReceipt> approve(String spender, BigInteger value) {
        Function function = new Function(
                FUNCTION_NAME_APPROVE,
                Arrays.asList(new Address(spender), new Uint256(value)),
                Collections.emptyList()
        );
        return executeRemoteCallTransaction(function);
    }

    public RemoteCall<Uint256> totalSupply() {
        Function function = new Function(
                FUNCTION_NAME_TOTAL_SUPPLY,
                Collections.emptyList(),
                Arrays.asList(new TypeReference<Uint256>() {
                })
        );
        return executeRemoteCallSingleValueReturn(function, Uint256.class);
    }

    public RemoteCall<Uint256> balanceOf(String owner) {
        Function function = new Function(
                FUNCTION_NAME_BALANCE_OF,
                Arrays.asList(new Address(owner)),
                Arrays.asList(new TypeReference<Uint256>() {})
        );
        return executeRemoteCallSingleValueReturn(function, Uint256.class);
    }
    public RemoteCall<Uint256> decimals() {
        Function function = new Function(
                "decimals",
                Collections.emptyList(),
                Arrays.asList(new TypeReference<Uint256>() {})
        );
        return executeRemoteCallSingleValueReturn(function, Uint256.class);
    }


}

ERC 完整demo下载地址

ERC 合约编辑地址 openzeppelin

POM.XML

        <dependency>
            <groupId>org.web3j</groupId>
            <artifactId>core</artifactId>
            <version>4.8.7</version>
        </dependency>
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.9.0</version>
        </dependency>

在springboot中 pom.xml

  <dependency>
            <groupId>org.web3j</groupId>
            <artifactId>web3j-spring-boot-starter</artifactId>
            <version>1.6.0</version>
        </dependency>
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.9.0</version>
        </dependency>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值