美文网首页
ETH 离线签名及代币离线签名

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

作者: Il_mondo | 来源:发表于2018-09-03 16:51 被阅读189次

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);
    }

相关文章

网友评论

      本文标题:ETH 离线签名及代币离线签名

      本文链接:https://www.haomeiwen.com/subject/ydliwftx.html