返回介绍

10.5. web3.eth

发布于 2023-06-19 14:14:32 字数 9006 浏览 0 评论 0 收藏 0

10.5. web3.eth

10.5.1. 查看账号列表

			
var Web3 = require('web3');
var web3 = new Web3('http://localhost:8545');

web3.eth.getAccounts().then(console.log);		
			
			

10.5.2. 查询矿工账号

			
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); 
    }
 })			
			
			

10.5.3. 获得余额

			
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}});
	};

});				
			
			

10.5.4. 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);
});			
			
			

10.5.5. web3.eth.sendSignedTransaction() 私钥签名转账

10.5.5.1. 例子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);
})			
			
				

10.5.5.2. 例子2

获取 pending 状态的区块

			
[ethereum@netkiller web3.example]$ vim test.js
[ethereum@netkiller web3.example]$ export PRIVATE_KEY=585a219fd6a5583b325e96770a88e69660f404efc06e56be71d82beedb7a989e
[ethereum@netkiller web3.example]$ echo $PRIVATE_KEY
585a219fd6a5583b325e96770a88e69660f404efc06e56be71d82beedb7a989e
[ethereum@netkiller web3.example]$ node
> process.env["PRIVATE_KEY"]
'585a219fd6a5583b325e96770a88e69660f404efc06e56be71d82beedb7a989e'
			
				
			
[ethereum@netkiller web3.example]$ cat transfer.js
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();
			
				
			
[ethereum@netkiller web3.example]$ node test.js
1.0.0-beta.34
Balance ETH: 8695480352861952

Balance before send: 100

gasPrice: 3000000000

Raw of Transaction:
{
	"from": "0xaa96686a050e4916afbe9f6d8c5107062fa646dd",
	"nonce": "0x20",
	"gasPrice": "0xb2d05e00",
	"gasLimit": "0xf4240",
	"to": "0x9ABcF16f6685fE1F79168534b1D30056c90B8A8A",
	"value": "0x0",
	"data": "0xa9059cbb000000000000000000000000372fda02e8a1eca513f2ee5901dc55b8b5dd741100000000000000000000000000000000000000000000000000000000000003e8",
	"chainId": "0x1"
}

Attempting to send signed tx:  f8a92084b2d05e00830f4240949abcf16f6685fe1f79168534b1d30056c90b8a8a80b844a9059cbb000000000000000000000000372fda02e8a1eca513f2ee5901dc55b8b5dd741100000000000000000000000000000000000000000000000000000000000003e825a05017058348d8f751cc40e71c13a63b8d8e21683841bd002c9f6bf691d34b6a4ba07df3fa8792aa66cc272ff89373509f6335272a4298e98177536a79c8ab7c947c

Receipt info:
{
	"blockHash": "0x32f45f27040b1df616ff4efd25557416793782541b995a6d4ecbd66f8441783f",
	"blockNumber": 5518045,
	"contractAddress": null,
	"cumulativeGasUsed": 5054117,
	"from": "0xaa96686a050e4916afbe9f6d8c5107062fa646dd",
	"gasUsed": 36184,
	"logs": [
		{
			"address": "0x9ABcF16f6685fE1F79168534b1D30056c90B8A8A",
			"topics": [
				"0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",
				"0x000000000000000000000000aa96686a050e4916afbe9f6d8c5107062fa646dd",
				"0x000000000000000000000000372fda02e8a1eca513f2ee5901dc55b8b5dd7411"
			],
			"data": "0x00000000000000000000000000000000000000000000000000000000000003e8",
			"blockNumber": 5518045,
			"transactionHash": "0x203ebcbe1cc8340c4b5a13f4e6c36a4f63142754437e0f43b0ff5e5c0bf512cc",
			"transactionIndex": 104,
			"blockHash": "0x32f45f27040b1df616ff4efd25557416793782541b995a6d4ecbd66f8441783f",
			"logIndex": 94,
			"removed": false,
			"id": "log_7ef3f104"
		}
	],
	"logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000100000000040000000000000000000000000000000008000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000002000000000000000000000000000000001200000000000000000000200000000000000000000000000000100000000000000000000000000000000000",
	"status": true,
	"to": "0x9abcf16f6685fe1f79168534b1d30056c90b8a8a",
	"transactionHash": "0x203ebcbe1cc8340c4b5a13f4e6c36a4f63142754437e0f43b0ff5e5c0bf512cc",
	"transactionIndex": 104
}

Balance after send: 1100
			
				

10.5.6. web3.eth.getBlock() 获取区块

获取 pending 状态的区块

			
web3.eth.getBlock(
    "pending",
function (error, block) {
    if (error) {
        console.error(error);
    } else {
        console.log(block.transactions.length); 
    }
})			
			
			

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文