离线签名工具说明

描述:此工具用来离线签名交易。

项目地址

https://github.com/youchainhq/youchainjs-tx

安装:

npm install youchainjs-tx

最新版:1.0.9

使用:

1.离线签名交易

const YOUTransaction = require('youchainjs-tx').YOUTransaction;
const privateKey = Buffer.from(
  'e331b6d69882b4cb4ea581d88e0b604039a3de5967688d3dcffdd2270c0fd109',
  'hex',
);

// 配置自定义选项
const Common = require('youchainjs-tx').Common;
const customCommon = Common.forCustomChain(
  'youchain',
  {
    name: 'youchain',
    networkId: 2,
  }
);

// 交易参数, 转账交易 data 字段数据为 0x
const txParams = {
  nonce: '0x00', // 可以通过 youchain.you.getTransactionCount 获取 nonce
  gasPrice: '0x09184e72a000',
  gasLimit: '0x2710',
  to: '0x0000000000000000000000000000000000000000',
  value: '0x00',
  data: '0x7f7465737432000000000000000000000000000000000000000000000000000000600057',
};

const tx = new YOUTransaction(txParams, { common: customCommon }); // 第二个参数为可选参数
tx.sign(privateKey);
const serializedTx = tx.serialize();

// 生成序列化交易
const rawTx = '0x' + serializeTx.toString('hex')

2.连接网络后发送交易

youchain.you
        .sendSignedTransaction(rawTx)
        .on('transactionHash', (hash) => {
            console.log('transactionHash', hash);
        })
        .on('receipt', (receipt) => {
            console.log('receipt', receipt);
        })
        .on('error', (error) => {
            console.log('error', error);
        });