当前位置:   article > 正文

Java使用web3j以太坊开发_java以太坊web3j开发

java以太坊web3j开发

Web3j 是一个高度模块化、反应式、类型安全的 Java 和 Android 库,用于处理智能合约并与以太坊网络上的客户端(节点)集成

引入依赖

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

2、工具类

/**
 * @author XiangYu
 * @since 2024/1/7
 */
@Slf4j
public class Web3Client {

    private static final  Web3j web3j = Web3j.build(new HttpService("主网/测试网rpc"));

    private Web3Client(){

    }

    /**
     * 发送交易、只能发送主网默认代币
     * @param privateKey 私钥
     * @param to to
     * @param value 金额
     * @return hash
     */
    public static String sendRawTransaction(String privateKey,String to,String value) {
        try {
            Credentials credentials = getCredentials(privateKey);

            BigDecimal amount = new BigDecimal(value);

            String signed = signed(web3j, to, credentials, amount);

            return web3j.ethSendRawTransaction(signed).send().getTransactionHash();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 发送交易
     *    发送token代币
     * @param privateKey 私钥
     * @param to 接收地址
     * @param amt 转账金额
     * @param contractAddress 合约地址
     * @return hash
     */
    public static String sendRawTransaction(String privateKey,String to,String amt,String contractAddress){
        try {
            Credentials credentials = getCredentials(privateKey);

            Function function = getFunction(to, amt);
            String encodedFunction = FunctionEncoder.encode(function);
            String hexSigned = signed(web3j,contractAddress, credentials, encodedFunction);

            EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexSigned).send();
            return ethSendTransaction.getTransactionHash();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 签名交易
     * @param web3j web3
     * @param to to
     * @param credentials 私钥凭证
     * @param value 金额
     * @return sign
     */
    private static String signed(String to, Credentials credentials,BigDecimal value) {
        BigInteger nonce = getNonce(web3j, credentials.getAddress());

        RawTransaction rawTransaction = RawTransaction.createTransaction(
                nonce,
                DefaultGasProvider.GAS_PRICE,
                DefaultGasProvider.GAS_LIMIT,
                to,
                Convert.toWei(value, Convert.Unit.ETHER).toBigInteger(),
                ""
        );

        return signed(credentials, rawTransaction);
    }

    /**
     * 签名
     * @param web3j web3
     * @param to to
     * @param credentials 凭证
     * @param encodedFunction 合约函数调用编码
     * @return 签名
     */
    private static String signed(String to, Credentials credentials, String encodedFunction) {
        BigInteger nonce = getNonce(web3j, credentials.getAddress());

        RawTransaction rawTransaction = RawTransaction.createTransaction(nonce,  DefaultGasProvider.GAS_PRICE,
                DefaultGasProvider.GAS_LIMIT, to, encodedFunction);

        return signed(credentials, rawTransaction);
    }

    /**
     * 签名
     * @param credentials 私钥凭证
     * @param rawTransaction 包装交易
     * @return hex sign
     */
    private static String signed(Credentials credentials, RawTransaction rawTransaction) {
        byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, Web3Manage.INSTANCE.getChainId(), credentials);
        return Numeric.toHexString(signedMessage);
    }

    /**
     * 包装智能合约的transfer函数方法
     * @param to 接收地址
     * @param amt 金额
     * @return transfer function
     */
    private static Function getFunction(String to, String amt) {
        Address address = new Address(to);
        Uint256 value = new Uint256(new BigInteger(Convert.toWei(amt, Convert.Unit.ETHER).toString()));
        List<Type> parametersList = new ArrayList<>();
        parametersList.add(address);
        parametersList.add(value);
        return new Function("transfer", parametersList, new ArrayList<>());
    }

    /**
     * 获取交易账户确认的nonce
     * @param web3j web3j
     * @param address 地址
     * @return nonce
     */
    public static BigInteger getNonce(String address) {
        try {
            EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(
                    address, DefaultBlockParameterName.LATEST).send();
            return ethGetTransactionCount.getTransactionCount();
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new BscRpcException("nonce too low");
    }

    /**
     * 通过私钥获取账户凭证
     * @param privateKey 私钥
     * @return 凭证
     */
    private static Credentials getCredentials(String privateKey) {
        BigInteger bigInteger = new BigInteger(privateKey, 16);
        ECKeyPair ecKeyPair = ECKeyPair.create(bigInteger);
        return Credentials.create(ecKeyPair);
    }

    /**
     * 钱包生成
     * @param walletFilePath 钱包生成路径
     * @return 凭证
     */
    public static Credentials genWallet(String walletFilePath){
        try {
            // 钱包密码
            String password = "";
            //生成钱包,对应目录下会创建对应的私钥文件。
            String walletFileName = WalletUtils.generateNewWalletFile(password, new File(walletFilePath), false);
            // 加载指定位置的钱包
            return WalletUtils.loadCredentials(password, walletFilePath + "/" + walletFileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 校验hash是否符合条件
     * @param hash 金额
     * @return bool
     */
    public static Transaction getTransactionHash(String hash){
        Web3j web3j = Web3Manage.INSTANCE.getWeb3j();
        try {
            // 获取交易信息
            EthTransaction ethTransaction = web3j.ethGetTransactionByHash(hash).send();
            return ethTransaction.getTransaction().orElse(null);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}

  • 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
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192

web3j.js文档
web3j文档
ethers.js文档
参考: Java使用Web3j进行基础和token转账

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

闽ICP备14008679号