在以太坊的钱包开发1中,我们介绍了node环境搭建、本地区块链节点的搭建与启动,下面开始实现钱包转账。
在app.js中,
var Web3 = require('web3');
if (typeof web3 !== 'undefined') {
web3 = new Web3(web3.currentProvider);
} else {
// set the provider you want from Web3.providers
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}
var version = web3.version.api;
console.log(version);
我们实例化了web3的对象,使用这个对象可以实现我们要的所有功能。
查看余额
web3.eth.getBalance('钱包地址', function(err,result) {
if (err == null) {
console.log('~balance:'+result);
}else {
console.log('~error:'+err);
}
});
查看交易
web3.eth.getTransaction('交易hash码',function (err, result) {
if (err == null) {
console.log('transaction:'+result);
} else {
console.log('error:'+err);
}
});
转账
此处需要载入ethereumjs-tx模块:
cd wallet
npm install ethereumjs-tx --save
var Tx = require('ethereumjs-tx');
var privateKey = new Buffer('钱包账户私钥', 'hex');
var rawTx = {
nonce: nonce,
gasPrice: '0x3b9aca00',
gasLimit: '0x493e0',
to: '收钱地址',
value: '金额数',
data: ''
};
var tx = new Tx(rawTx);
tx.sign(privateKey);
var serializedTx = tx.serialize();
web3.eth.sendRawTransaction('0x' + serializedTx.toString('hex'), function(err, hash) {
console.log('交易结果:'+hash);
if (callback && typeof(callback) === "function") {
if (!err)
callback(null, hash);
else
callback(err, null);
}
});
node app.js //执行
这里要注意nonce的使用,nonce是指同一个账号在同一个节点下,发起的交易排序号。nonce从0开始算起,每次加一。如果你的账号当前nonce是10,你发起了nonce为12的交易A,那么只有nonce为10、11的交易完成了,才轮到nonce为12的交易A。中间如果这个节点重启了,那么这个交易A就会被取消掉。建议用web3.eth.getTransactionCount(‘你的钱包地址’) 来获取当前nonce,每次加一。
后续,使用NodeJS开发接口给前端、移动端使用。。
参考:https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethgettransactioncount