web3.js¶
连接到以太坊客户端:
1. http 方式
var Web3 = require('web3');
var web3 = new Web3('http://localhost:8545');
2. WebSocket 方式
var Web3 = require('web3');
var web3 = new Web3(Web3.givenProvider || 'ws://remotenode.com:8546');
3. IPC 方式
// Using the IPC provider in node.js
var net = require('net');
var Web3 = require('web3');
var web3 = new Web3('/Users/myuser/Library/Ethereum/geth.ipc', net); // mac os path
查看账号列表:
var Web3 = require('web3');
var web3 = new Web3('http://localhost:8545');
web3.eth.getAccounts().then(console.log);
查询矿工账号:
var Web3 = require('web3');
var web3 = new Web3('http://localhost:8545');
web3.eth.getCoinbase().then(console.log);
// Callback 方式
web3.eth.getCoinbase(
function(error, result){
if (error) {
console.error(error);
} else {
console.log(result);
}
})
获得余额:
web3.eth.getBalance(req.query.address).then(function(balance){
res.json({"status": true, "code":0, "data":{"account":req.query.address, "balance": web3.utils.fromWei(balance)}});
});
// Callback 方式
web3.eth.getBalance(req.query.address, function (error, wei) {
if (!error) {
var balance = web3.utils.fromWei(wei, 'ether');
res.json({"status": true, "code":0, "data":{"account":req.query.address, "balance": balance}});
}else{
console.log(error);
res.json({"status": false, "code":1, "data":{"error":error.message}});
}
});
// 捕捉错误
router.get('/balance.json', function(req, res) {
try {
web3.eth.getBalance(req.query.address, function (error, wei) {
if (!error) {
var balance = web3.utils.fromWei(wei, 'ether');
res.json({"status": true, "code":0, "data":{"account":req.query.address, "balance": balance}});
}else{
console.log(error);
res.json({"status": false, "code":1, "data":{"error":error.message}})
}
});
}
catch(error){
res.json({"status": false, "code":1, "data":{"error":error.message}});
};
});
web3.eth.sendTransaction():
web3.eth.sendTransaction({
from: coinbase,
to: '0x2C687bfF93677D69bd20808a36E4BC2999B4767C',
value: web3.utils.toWei('2','ether')
},
function(error, result){
if(!error) {
console.log("#" + result + "#")
} else {
console.error(error);
}
});
var code = "0x603d80600c6000396000f3007c01000000000000000000000000000000000000000000000000000000006000350463c6888fa18114602d57005b6007600435028060005260206000f3";
web3.eth.sendTransaction({from: coinbase, data: code}, function(err, transactionHash) {
if (!err)
console.log(transactionHash); // "0x7f9fade1c0d57a7af66ab4ead7c2eb7b11a91385"
});
web3.eth.sendTransaction({from: coinbase, data: code}).then(function(receipt){
console.log(receipt);
});
web3.eth.sendSignedTransaction() 私钥签名转账:
例子1:
var account = web3.eth.accounts.privateKeyToAccount(privateKey);
web3.eth.accounts.signTransaction({
from: account.address,
to: "0x0013a861865d74b13ba94713d4e84d97c57e7081",
gas: "3000000",
value: '100000000000000000',
gasPrice: '0x09184e72a000',
data: "0x00"
}, account.privateKey)
.then(function(result) {
console.log("Results: ", result)
web3.eth.sendSignedTransaction(result.rawTransaction)
.on('receipt', console.log);
})
fs = require('fs');
const Web3 = require('web3');
var Tx = require('ethereumjs-tx');
const web3 = new Web3('http://localhost:8545');
console.log(web3.version)
coinbase = "0xaa96686a050e4916afbe9f6d8c5107062fa646dd";
address = "0x372fda02e8a1eca513f2ee5901dc55b8b5dd7411"
contractAddress = "0x9ABcF16f6685fE1F79168534b1D30056c90B8A8A"
const main = async () => {
var balance = await web3.eth.getBalance(coinbase);
console.log(`Balance ETH: ${balance} \n`);
const abi = fs.readFileSync('output/NetkillerToken.abi', 'utf-8');
const contract = new web3.eth.Contract(JSON.parse(abi), contractAddress, { from: address});
var balance = await contract.methods.balanceOf(address).call();
console.log(`Balance before send: ${balance} \n`);
var count = await web3.eth.getTransactionCount(coinbase);
const gasPrice = await web3.eth.getGasPrice();
console.log(`gasPrice: ${gasPrice}\n`)
var gasLimit = 1000000;
var transferAmount = 1000;
// Chain ID of Ropsten Test Net is 3, replace it to 1 for Main Net
var chainId = 1;
var rawTransaction = {
"from": coinbase,
/* "nonce": "0x" + count.toString(16),*/
"nonce": web3.utils.toHex(count),
"gasPrice": web3.utils.toHex(gasPrice),
"gasLimit": web3.utils.toHex(gasLimit),
"to": contractAddress,
"value": "0x0",
"data": contract.methods.transfer(address, transferAmount).encodeABI(),
"chainId": web3.utils.toHex(chainId)
};
console.log(`Raw of Transaction: \n${JSON.stringify(rawTransaction, null, '\t')}\n`);
// The private key for myAddress in .env
var privateKey = new Buffer(process.env["PRIVATE_KEY"], 'hex');
var tx = new Tx(rawTransaction);
tx.sign(privateKey);
var serializedTx = tx.serialize();
// Comment out these four lines if you don't really want to send the TX right now
console.log(`Attempting to send signed tx: ${serializedTx.toString('hex')}\n`);
var receipt = await web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'));
// The receipt info of transaction, Uncomment for debug
console.log(`Receipt info: \n${JSON.stringify(receipt, null, '\t')}\n`);
// The balance may not be updated yet, but let's check
var balance = await contract.methods.balanceOf(address).call();
console.log(`Balance after send: ${balance}`);
}
main();
web3.eth.getBlock() 获取区块:
// 获取 pending 状态的区块
web3.eth.getBlock(
"pending",
function (error, block) {
if (error) {
console.error(error);
} else {
console.log(block.transactions.length);
}
});
账号管理:
var coinbase = "0x5c18a33DF2cc41a1bedDC91133b8422e89f041B7";
//console.log(coinbase)
web3.eth.personal.unlockAccount(coinbase, "your password").then(console.log);
// 查询默认帐户余额
> web3.fromWei(eth.getBalance(eth.coinbase), "ether")
// 查询第2个帐户余额
web3.fromWei(eth.getBalance(eth.accounts[1]),"ether")