当前位置: 首页 > 工具软件 > web3j > 使用案例 >

Java使用Web3j进行基础和token转账

斜瑞
2023-12-01

这里使用的是maven项目,第一步要引入web3j的包

引入pom

 <dependency>
        <groupId>org.web3j</groupId>
        <artifactId>core</artifactId>
        <version>3.4.0</version>
    </dependency>
 

基础转账

    public static void transfer() throws Exception {
        Web3j web3j = Web3j.build(new HttpService("infura节点链接"));
        BigInteger bigInteger = new BigInteger("钱包私钥", 16);
        ECKeyPair ecKeyPair = ECKeyPair.create(bigInteger);
        Credentials credentials = Credentials.create(ecKeyPair);
        TransactionReceipt transactionReceipt = Transfer.sendFunds(web3j, credentials, "目标地址", BigDecimal.valueOf(0.001), Convert.Unit.ETHER).send();
        System.out.println(transactionReceipt);
    }

Token转账

    public static void transferToken() throws Exception {
        Web3j web3j = Web3j.build(new HttpService("infura节点链接"));
        BigInteger bigInteger = new BigInteger("私钥", 16);
        ECKeyPair ecKeyPair = ECKeyPair.create(bigInteger);
        Credentials credentials = Credentials.create(ecKeyPair);
        String fromAddress = credentials.getAddress();
        EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(
                fromAddress, DefaultBlockParameterName.LATEST).sendAsync().get();
        BigInteger nonce = ethGetTransactionCount.getTransactionCount();

        Address address = new Address("目标地址");
        Uint256 value = new Uint256(new BigInteger("数量 单位wei"));
        List<Type> parametersList = new ArrayList<>();
        parametersList.add(address);
        parametersList.add(value);
        List<TypeReference<?>> outList = new ArrayList<>();
        Function function = new Function("transfer", parametersList, outList);
        String encodedFunction = FunctionEncoder.encode(function);
        System.out.println( DefaultGasProvider.GAS_PRICE);
        System.out.println(DefaultGasProvider.GAS_LIMIT);
        RawTransaction rawTransaction = RawTransaction.createTransaction(nonce,  DefaultGasProvider.GAS_PRICE,
                new BigInteger("210000"), "合约地址", encodedFunction);
        byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
        String hexValue = Numeric.toHexString(signedMessage);
        EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).sendAsync().get();
        Object transactionHash = ethSendTransaction.getTransactionHash();
        System.out.println(transactionHash.toString());
    }

参考文档

web3.js 中文文档
web3j 英文文档

笔者整理了常见的一些智能合约并进行分类。

 类似资料: