在以太坊的钱包开发1 <https://blog.csdn.net/u011494083/article/details/79654872>
中,我们介绍了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 walletnpm 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);
varserializedTx = 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    //执行







后续,开发接口给前端、移动端使用。。




参考:
https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethgettransactioncount
<https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethgettransactioncount>

友情链接
KaDraw流程图
API参考文档
OK工具箱
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:637538335
关注微信