当前位置:   article > 正文

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

web3j转账

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

引入pom

 <dependency>
        <groupId>org.web3j</groupId>
        <artifactId>core</artifactId>
        <version>3.4.0</version>
    </dependency>
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

基础转账

    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);
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

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());
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

参考文档

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

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/574645
推荐阅读
相关标签
  

闽ICP备14008679号