ETH 离线签名及代币离线签名

ETH 签名

    public static String signedEthTransactionData(
            String privateKey, String to, BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit, String value) {
        // 把十进制的转换成ETH的Wei, 1ETH = 10^18 Wei
        BigDecimal realValue = Convert.toWei(value, Convert.Unit.ETHER);
        RawTransaction rawTransaction = RawTransaction.createEtherTransaction(nonce, gasPrice, gasLimit, to, realValue.toBigIntegerExact());

        // 手续费= (gasPrice * gasLimit ) / 10^18 ether
        Credentials credentials = Credentials.create(privateKey);

        // 使用TransactionEncoder对RawTransaction进行签名操作
        byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);

        // 转换成0x开头的字符串
        return Numeric.toHexString(signedMessage);
    }

ETH代币签名

    public static String signedEthContractTransactionData(
            String privateKey, String contractAddress, String to, BigInteger nonce, BigInteger gasPrice,
            BigInteger gasLimit, Double value, Double decimal) {

        // 因为每个代币可以规定自己的小数位, 所以实际的转账值 = 数值 * 10^小数位
        BigDecimal realValue = BigDecimal.valueOf(value * Math.pow(10.0, decimal));

        // 0xa9059cbb代表某个代币的转账方法hex(transfer) + 对方的转账地址hex + 转账的值的hex
        String data = "0xa9059cbb" + Numeric.toHexStringNoPrefixZeroPadded(Numeric.toBigInt(to), 64)
                + Numeric.toHexStringNoPrefixZeroPadded(realValue.toBigInteger(), 64);
        RawTransaction rawTransaction = RawTransaction.createTransaction(nonce, gasPrice, gasLimit, contractAddress, data);

        // 手续费= (gasPrice * gasLimit ) / 10^18 ether
        Credentials credentials = Credentials.create(privateKey);

        // 使用TransactionEncoder对RawTransaction进行签名操作
        byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);

        // 转换成0x开头的字符串
        return Numeric.toHexString(signedMessage);
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容