以太坊钱包的开发2 -- web3的应用

以太坊的钱包开发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    //执行



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


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

猜你喜欢

转载自blog.csdn.net/u011494083/article/details/79655830