发送交易需要签名, 这就涉及到账号的管理. 账号管理的方式有很多, 基于keystore的, 或者基于助记词的等. 此处我们focus on发送交易本身, 所以直接使用明文的privatekey. 在真正的app中当然不推荐这么做.
发送交易是, wanchain有一个npm包 wanchain-util封装了最基本的功能, 推荐使用node10, web3@0.20. 代码如下.
'use strict'
const Web3 = require("web3");
const wanUtil = require('wanchain-util');
var Tx = wanUtil.wanchainTx;
var web3 = new Web3(new Web3.providers.HttpProvider("http://52.42.145.155:36891"));
let myAddr = '0x65Bc523Ae5C53f546dF832751516132643dFc4F0'
let toAddr = '0x8e12f79275b1c251b0eb5753d18b8a0bfdd8f7cb';
let privateKey = '5b892259093d58616711b1ae0ea42de1dba1fa4536ef6521e6b6986d819f8ac3'
let gGasLimit=22000;
let gGasPrice=200000000000; // 200G
let nonce = web3.eth.getTransactionCount(myAddr);
var rawTx = {
Txtype: 0x01,
nonce: nonce,
gasPrice: gGasPrice,
gasLimit: gGasLimit,
to: toAddr,
chainId: 3,
value: '0x02'
};
const tx = new Tx(rawTx);
tx.sign(Buffer.from(privateKey,'hex'));
const serializedTx = tx.serialize();
web3.eth.sendRawTransaction("0x"+serializedTx.toString('hex'), (err, hash)=>{
if( err) {
console.log("transfer error: ", err);
} else {
console.log(hash);
}
});